Validating input with while loop and scanner

2019-04-17 11:58发布

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. 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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-17 12:50

Where do you change choice inside of your while loop? If it's not changed you can't expect to use it in your if block's boolean condition.

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.

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
查看更多
Root(大扎)
3楼-- · 2019-04-17 12:53

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..

查看更多
登录 后发表回答