我試圖要求用戶輸入兩個數字。我想檢查這些輸入是否實際上是數字,但是如果第一個輸入是字符串,我迄今爲止的代碼不會讓我輸入第二個值。掃描儀不讀取其他語句中的輸入
因此,掃描儀不會讀取任何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