How do I stop while loop from running infinitely?

江枫思渺然 提交于 2019-12-24 02:43:24

问题


Can't figure out how to stop this while loop from repeating infinitely. I'm using hasNextInt to check if user input is an int. If an int is not entered the loop repeats infinitely.

public static void validatingInput(){
    Scanner scan = new Scanner(System.in);

    boolean valid = false;
    int userNumber = 0;

    while(!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
    userNumber = scan.nextInt();
    valid = true;   
    } else 
        System.out.print("Not an int. ");
    }

}

回答1:


You need to consume a token from a scanner in order to allow it to read the next token:

while (!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
        userNumber = scan.nextInt();
        valid = true;   
    } else 
        System.out.print("Not an int. ");
        scan.next(); // Skip a token
    }
}



回答2:


You can break any loops with break;. Check the state of an input and break the while when you want



来源:https://stackoverflow.com/questions/55444997/how-do-i-stop-while-loop-from-running-infinitely

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