简体   繁体   中英

Do while infinite loop

I am trying to write a method that asks a user for a positive integer. If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value". This part is not the issue. The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.

Here is my code:

private static int nonNegativeInt(){
        boolean properValue = false;
        int variable = 0;
        do {
            try {
                while (true) {
                    variable = scanner.nextInt();
                    if (variable < 0) {
                        System.out.println("Please enter a positive value");
                    } else if (variable >= 0) {
                        break;
                    }
                }
                properValue = true;
            } catch (InputMismatchException e){
                System.out.println("That is not a valid value.");
            }
        } while (properValue == false);
        return variable;
    } 

Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value. When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.

What you want to do is add the line

scanner.next(); 

in your catch clause to basically say skip over that token.

Side note: Your method in general is unnecessarily long. You can shorten it into this.

private static int nonNegativeInt() {
    int value = 0;
    while (true) {
        try {
            if ((value = scanner.nextInt()) >= 0)
                return value;
            System.out.println("Please enter a positive number");
        } catch (InputMismatchException e) {
            System.out.println("That is not a valid value");
            scanner.next();
        }
    }
}

you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever. Adding properValue = true; or even a break statement inside the catch statement gives you the required functionality!

I hope I helped!

Just add a break statement inside your catch.
Btw, you can get rid of the while loop by rewriting it like this:

try {
    variable = scanner.nextInt();
    if (variable < 0) {
        System.out.println("Please enter a positive value");
    } else {
        properValue = true;
    }
}
//... 

You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.

private static int nonNegativeInt(){
    boolean properValue = false;
    int variable = 0;
    do {
        scanner = new Scanner(System.in);
        try {
            while (true) {
                variable = scanner.nextInt();
                if (variable < 0) {
                    System.out.println("Please enter a positive value");
                } else if (variable >= 0) {
                    break;
                }
            }
            properValue = true;
        } catch (InputMismatchException e){
            System.out.println("That is not a valid value.");
        }
    } while (properValue == false);
    return variable;
} 

This is indeed nearly identical to SO: Java Scanner exception handling

Two issues:

  • You need a scanner.next(); in your exception handler

    ... AND ...

  • You don't really need two loops. One loop will do just fine:

     private static int nonNegativeInt(){ boolean properValue = false; int variable = 0; do { try { variable = scanner.nextInt(); if (variable < 0) { System.out.println("Please enter a positive value"); continue; } else if (variable >= 0) { properValue = true; } } catch (InputMismatchException e){ System.out.println("That is not a valid value."); scanner.next(); } } while (properValue == false); return variable; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM