我正在编写一个非常简单的程序,从用户那里获得3个into,并希望在将它们存储到单独的变量中进行处理之前,检查它们是否都是into。我使用的检查对第一个输入有效,但是失败,并在第二个输入中抛出异常。
boolean properInt = scanner.hasNextInt();
int largest = Integer.MAX_VALUE;
boolean anError = false;
while(properInt=false){
anError=true;
System.out.println("Invalid number...whole numeric values only");
}
while(properInt =true){
int a= scanner.nextInt();
System.out.println("you entered "+ a);
int b = scanner.nextInt();
System.out.println("you entered "+ b);
int c= scanner.nextInt();
System.out.println("you entered "+ c);
}
发布于 2019-01-13 16:10:34
原因是当您使用任何一个nextXxx(...)
时,扫描器光标会被重置到调用之前的位置。输入有效数字后按下“enter”键时,扫描仪将忽略“字符”(enter)。但是,当输入无效值时,会引发异常,下一个“nextInt
”将enter键字符视为另一个条件,因此无法工作。
我建议使用nextLine
,然后使用Integer.ParseInt
和捕捉NumberFormatException
。
同时,您的while循环检查是不正确的。
properInt=false is a statement.
while(properInt==false) is a condition..
英语不是我的强项,所以如果它让我困惑的话,请告诉我。
https://stackoverflow.com/questions/54174269
复制