我试图要求用户输入两个数字。我想检查这些输入是否实际上是数字,但是如果第一个输入是字符串,我迄今为止的代码不会让我输入第二个值。扫描仪不读取其他语句中的输入
因此,扫描仪不会读取任何else语句。
我怎么能使它工作?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
您的'else'块只包含一个打印语句。 –
添加到以前的评论中,将'else'条件放在'{}'块中应该有所帮助。 – Eugene
我已经试过了。可悲的是,这并没有帮助。任何其他想法? – kiaora