Scanner keeps skipping input whist using nextInt() and loops

回眸只為那壹抹淺笑 提交于 2019-11-27 08:37:55

问题


I am using a while loop to make sure that the value entered to a scanner object is an integer as such:

while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
        }
    }

however, if the user does not enter an integer, when it should go back and take another input it just repeatedly prints "Capacity" followed by the output in the catch without asking for more input. How do I stop this?


回答1:


scan.nextLine();

Put this piece of code inside your catch block, to consume the non integer character along with the new line character which is stays in the buffer(hence, infinitely printing the catch sysout), in the case where you've given a wrong input.

Ofcourse, there are other cleaner ways to achieve what you want, but I guess that will require some refactoring in your code.




回答2:


Use the following:

while (!capacityCheck) {
        System.out.println("Capacity");
        String input = scan.nextLine();
        try {
            capacity = Integer.parseInt(input );
            capacityCheck = true;
        } catch (NumberFormatException e) {
            System.out.println("Capacity must be an integer");
        }
    }



回答3:


Try this :

while (!capacityCheck) {
    try {
        System.out.println("Capacity");
        capacity = scan.nextInt();
        capacityCheck = true;
    } catch (InputMismatchException e) {
        System.out.println("Capacity must be an integer");
        scan.nextLine();
    }
}



回答4:


Try putting this at the end of the loop -

scan.nextLine();

Or better to put it in the catch block.

    while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
            scan.nextLine();
        }
    }



回答5:


I see no need for a try/catch or capacityCheck as we have access to the method hasNextInt() - which checks if the next token is an int. For instance this should do what you want:

    while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token.
        System.out.println("Capacity must be an integer");
        scan.next();
    }
    capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.


来源:https://stackoverflow.com/questions/15516036/scanner-keeps-skipping-input-whist-using-nextint-and-loops

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