我正在尝试使用scanner
对象来验证一些用户输入。根据我的要求,如果用户输入 100>输入< 0 ,我需要提供一些控制台输出。但是,当我输入100/0并为我提供一些空的控制台输出时,以下代码不起作用。我尝试使用102和-1测试此代码块,并使用相同(空)控制台输出
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
}else if (sc.nextInt() > 100){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else if (sc.nextInt() < 0){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else {
score = sc.nextInt();
break;
}
}
return score;
}
答案 0 :(得分:4)
由于在if else块中使用了nextInt(),导致错误。使用方法hasNextInt()并在验证值之前将值存储在临时变量中。
答案 1 :(得分:2)
您不应多次阅读Scanner
。只需通过nextInt
将数字读入变量并检查即可。否则,在每个if
分支上,系统将提示您输入新号码。
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}