简体   繁体   English

使用while循环和扫描仪验证输入

[英]Validating input with while loop and scanner

What's the best way about getting a valid integer from a user that is in a specified range (0,20) and is an int . 从指定范围(0,20)的用户获取有效整数并且是int的最佳方法是什么。 If they enter an invalid integer print out error. 如果他们输入无效的整数打印输出错误。

I am thinking something like: 我想的是:

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

Is this correct or is there a better way? 这是正确的还是有更好的方法?

You can do something like this: 你可以这样做:

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;
}

This program will keep asking for an input until it gets a valid one. 该程序将继续询问输入,直到它获得有效输入。

Make sure you understand every step of the program.. 确保您了解该计划的每一步......

Where do you change choice inside of your while loop? 你在哪里改变你的while循环中的选择? If it's not changed you can't expect to use it in your if block's boolean condition. 如果它没有改变,你不能指望在你的if块的布尔条件中使用它。

You'll have to check that the Scanner doesn't have an int and if it does have an int, get choice and check that separately. 你必须检查的扫描仪没有一个int,如果它确实有一个int,得到的选择和检查分开。

Pseudocode: 伪代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM