0

从指定范围(0,20)内的用户获取有效整数并且是int. 如果他们输入无效的整数,则打印出错误。

我在想类似的事情:

 int choice = -1;
 while(!scanner.hasNextInt() || choice < 0 || choice > 20) {
       System.out.println("Error");
       scanner.next(); //clear the buffer
 }
 choice = scanner.nextInt();

这是正确的还是有更好的方法?

4

2 回答 2

1

你可以这样做:

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a valid number: ");
    while (!sc.hasNextInt()) {
       System.out.println("Error. Please enter a valid number: ");
       sc.next(); 
    }
    number = sc.nextInt();
} while (!checkChoice(number));

private static boolean checkChoice(int choice){
    if (choice <MIN || choice > MAX) {     //Where MIN = 0 and MAX = 20
        System.out.print("Error. ");
        return false;
    }
    return true;
}

这个程序会一直要求输入,直到它得到一个有效的输入。

确保您了解程序的每一步。

于 2013-03-03T06:35:39.750 回答
1

您在 while 循环中在哪里更改选择?如果它没有改变,你不能期望在你的 if 块的布尔条件中使用它。

您必须检查 Scanner 是否没有 int,如果确实有 int,请选择并单独检查。

伪代码:

set choice to -1
while choice still -1
  check if scanner has int available
    if so, get next int from scanner and put into temp value
    check temp value in bounds
    if so, set choice else error
  else error message and get next scanner token and discard
done while
于 2013-03-03T06:49:54.413 回答