Scanner keeps skipping input whist using nextInt() and loops

只谈情不闲聊 提交于 2019-11-28 14:25:14
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.

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

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

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

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