简体   繁体   中英

While loop that is not working with Try/Catch statements

Im trying to give the user the opportunity to repeat an input after introducing something that has produced an error but something is not working because once the err is caught the try stuff is not executed again, instead it goes directly to the catch stuff generating an eternal cicle. Here is my code:

while (err==1){
    err=0;
    try{
        dim = keyboard.nextInt();
    } catch(Exception e){
        System.out.println("Oops! What you entered is not an integer.");
        err=1;
    }
}

When you enter a non-integer the Scanner call to nextInt() doesn't consume the non-integer. You need to call keyboard.next() (or keyboard.nextLine() ) to consume it. Something like,

try {
    dim = keyboard.nextInt();
} catch (Exception e) {
    System.out.printf("%s is not an integer.%n", keyboard.next());
    err = 1;
}

You are not clearing/flushing the scanner buffer after each user input.

  • Use keyboard.nextLine() just before the end of while loop(after the catch block)

    OR

  • Declare the scanner object inside the while loop itself Scanner keyboard = new Scanner(System.in);

See this

Cheers!

The problem is with the input.nextInt() command it only reads the int value. It would be even better, if you read the input through Scanner#nextLine and convert your input to integer using Integer#parseInt(String) method.

This does work for me.

 public static void main(String[] args) {
    int err = 1;
    Scanner keyboard = new Scanner(System.in);
    while (err == 1) {
        err = 0;
        try {
            int dim = Integer.parseInt(keyboard.nextLine());
            System.out.println("done.. exit");
        } catch (Exception e) {
            System.out.println("Ups! What you entered is not an integer.");
            err = 1;
        }
    }
}

output

dd
Ups! What you entered is not an integer.
23
done.. exit

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \\n). Once the input is read, nextLine() positions the cursor in the next line.

for reading the entire line you can use nextLine()

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