Snailwalker Snailwalker - 16 days ago 6
Java Question

Try catch inside of a while loop throw an exception

I just implemented this program by using "try catch" inside of a while loop. The idea is to notify user if the input is not an integer then ask user input the new value again. The problem I have is that after I input some random string, It throws out an exception at the console. I couldn't find a post that is related to this issue. Any ideas ? Thank you in advance !

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)


import java.util.Scanner;

public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long num = 0;
while (true) {
try {
System.out.println("Enter big int: ");
num = scan.nextLong();
break;
} catch (Exception e) {
System.out.println("Warning: Wrong input!! Please enter an integer again: ");
num = scan.nextLong();
scan.close();
}
}
for (int row = 0; row < 5; row++) {
long temp = num;
for (int skip = 0; skip < 5; skip++) {
if (skip >= row)
System.out.print((temp % 10) + "\t");
temp /= 10;
}
System.out.println("");
}
}
}

Answer

As said by RealSkeptic in the comments ,

If you don't clear the bad input from the scanner, it will stay there, and throw an exception every time. You need to use scan.next(). Oh, and don't close it if you want to read the next number...

So first you have to clear that input buffer from Scanner. For that you can read that line and just discard it using scan.next() in the catch block.

while (true) {
            try {
                System.out.println("Enter big int: ");
                num = scan.nextLong();
                break;
            } catch (Exception e) {
                System.out.println("Warning: Wrong input!! Please enter an integer again: ");
                scan.next();
            }
        }

This will work for you.

Comments