Validating input with while loop and scanner

强颜欢笑 提交于 2019-12-04 21:59:21

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!