Scanner keeps skipping input whist using nextInt() and loops

后端 未结 5 1179
情深已故
情深已故 2020-12-12 04:13

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 {
            Sys         


        
相关标签:
5条回答
  • 2020-12-12 04:40

    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();
            }
        }
    
    0 讨论(0)
  • 2020-12-12 04:44
    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.

    0 讨论(0)
  • 2020-12-12 04:46

    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.
    
    0 讨论(0)
  • 2020-12-12 04:47

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-12 04:57

    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");
            }
        }
    
    0 讨论(0)
提交回复
热议问题