itamar8910
itamar8910

Reputation: 305

Java catch statement in loop does not work

When I run th code, and say input 2.5, the output I get is:

2.5, 4 times "error", and 5.

It means that the computer goes through the catch statement every time, instead of asking for input every time it loops through the while loop and enters the try block.

public static void main(String[] args)
{
    Scanner s1 = new Scanner(System.in);
    int n = 0;
    while(n<5)
    {
        try
        {
            int grade = s1.nextInt();
            System.out.println(grade);
        }
        catch(Exception e)
        {
            System.out.println("error");
        }
        n++;
    }
    System.out.println(n);
}

Upvotes: 1

Views: 110

Answers (3)

sourb
sourb

Reputation: 146

According to the documentation:

This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

This means that if the translation is NOT successful, the scanner does not advance past the input. It keeps trying to translate .5 in every iteration.

You can get the result I assume you expect by adding s1.next() in your catch statement to clear the token in the Scanner:

public static void main(String[] args)
{
    Scanner s1 = new Scanner(System.in);
    int n = 0;
    while(n<5)
    {
        try
        {
            int grade = s1.nextInt();
            System.out.println(grade);
        }
        catch(Exception e)
        {
            **s1.next();**
            System.out.println("error");
        }
        n++;
    }
    System.out.println(n);
}

And as many have already mentioned, output all possible information from exception!

Upvotes: 0

ajb
ajb

Reputation: 31689

Basically, there is a "cursor" that points to the next character of your input line that a Scanner will read. If the input line looks like

bad input

the cursor starts before the b. If you call nextInt(), the Scanner will throw an exception, because b can't be the start of an integer. But the cursor stays in the same place. So next time you call nextInt(), the same error will happen all over again.

You need to do something that will "consume" the bad input so that the cursor will move. s1.nextLine(), as in almas' answer, will consume the entire rest of the line.

If the input is

2.5

nextInt() will throw an exception because 2.5 is not an integer. Once again, the cursor stays in the same place, so the error will keep coming up, unless you do something to consume the 2.5. If you want the program to actually read 2.5, then don't use nextInt() since 2.5 is not an integer.

Upvotes: 0

Christian Hujer
Christian Hujer

Reputation: 17945

When you enter "2.5", nextInt() consumes the 2. The next thing being scanned by the very same nextInt() will be . and that cannot be successfully scanned by nextInt(), so you get the error. nextInt() can only be used to scan int numbers, if you want to scan fractions like 2.5, you need nextDouble().

By the way, the exception objects hold useful information. If you do this, you're just hiding the error information:

catch (Exception e) {
    System.err.println(error):
}

Instead do this:

catch (Exception e) {
    e.printStackTrace();
}

And don't mix System.out and System.err. System.out is for the normal program output but not for logging, debug, info, warning, error or such messages. Those should go to System.err.

Upvotes: 3

Related Questions