Java Scanner.nextInt() gets skipped?



我编写了一些代码,需要一个int变量来保存0到5之间的值,并且我编写了一个while循环来验证用户输入的值是否有效(0到5),如下所示:

import java.util.Scanner;
public class ZeroToFive {
public static void main(String[] args) {
//some code...
Scanner scanner = new Scanner (System.in);
int someNumber = -1;  
while(someNumber < 0 || someNumber > 5)
System.out.println("Enter a number from 0 to 5");
someNumber=scanner.nextInt();
if(someNumber < 0 || someNumber > 5){
System.out.println("Invalid data. You must enter a number from 0 to 5. Try again.");
}
// some code that needs someNumber to be a number from 0 to 5...       
} 
}

计划是用用户输入更新someNumber变量,但是循环继续运行而不停止读取nextInt()。

输出:输入0 ~ 5之间的数字输入0 ~ 5之间的数字输入0 ~ 5之间的数字输入0 ~ 5之间的数字输入0 ~ 5之间的数字…(永远)

为什么循环不停下来从用户那里读取nextInt() ?

问题是由于while循环缺少{...}

应该是

while (someNumber < 0 || someNumber > 5) {
System.out.print("Enter a number from 0 to 5: ");
someNumber = scanner.nextInt();
if (someNumber < 0 || someNumber > 5) {
System.out.println("Invalid data. You must enter a number from 0 to 5. Try again.");
}
// some code that needs someNumber to be a number from 0 to 5... 
}

由于缺少括号,只有下面的语句

System.out.println("Enter a number from 0 to 5");

while循环范围内。

所以,基本条件while(someNumber < 0 || someNumber > 5)总是正确的,因为你发起的变量"someNumber"值1。你要做的是在while指令中使用分号同时包含System.out.println("Enter a number from 0 to 5");someNumber=scanner.nextInt();,以便让someNumber变量改变其值。

代码应该是这样的:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//some code...
Scanner scanner = new Scanner (System.in);
int someNumber = -1;
while(someNumber < 0 || someNumber > 100){
System.out.println("Enter a number from 0 to 5");
someNumber=scanner.nextInt();
}
if(someNumber < 0 || someNumber > 5){
System.out.println("Invalid data. You must enter a number from 0 to 5. Try again.");
}
// some code that needs someNumber to be a number from 0 to 5...
}
}

相关内容

  • 没有找到相关文章

最新更新