-1
    try
        {
             n = s.nextLine();
             a = s.nextInt();
        }
        catch(Exception e)
        {
            System.out.println("do u really want to come out? Write True or False");
            boolean c = s.nextBoolean();
            }

when i debug this code it does exactly what i want. but when i run it it doesnt let me do s.nextboolean(which s is an object of scanner(java.util.Scanner). i'm using it to get an input). what happens if that when the exception happens it prints do u really want to come out? Write True or False but then it prints the exception and crashes the code. it doesnt let me type True or False, it just crashes it.t in the code when it asks for an int and you give a string it should come out, so it gives a mismatch exception. is this a bug(i'm using intellij)

AJNeufeld
  • 8,231
  • 1
  • 22
  • 40
  • 2
    When you get an invalid input, you are not consuming it e.g. `nextLine()` so when you try `nextBoolean()` you are still trying to read the invalid input. – Peter Lawrey Nov 25 '16 at 21:54
  • 1
    @PeterLawrey that's what I was thinking, too. @artechhelp so just add `nextLine()` before `nextBoolean()`. – Logan Nov 25 '16 at 21:55
  • thanks. i thought nextline was just supposed to make it if u wanted to enter a string? – slayerofthend Nov 25 '16 at 22:02
  • 1
    It is, but using methods like `nextInt()` and `nextBoolean()` do not consume the newline (`\n`) character like `nextLine()` does. I often read in all my values with `nextLine()`, and parse them so I don't have to worry about this issue. – Logan Nov 25 '16 at 22:04

1 Answers1

0

Lets assume you type in "FRED" for your integer value, and press Enter. Your input stream will look like this:

F R E D \n

s.nextInt() finds the first character in the input stream is not an Integer, so it throws a InputMismatchException, and does not consume any characters. So your input stream still looks like this:

F R E D \n

You call s.nextBoolean(), and again, a InputMismatchException is raised. This time, you are not inside a try { ... } block (you are inside the catch block), so the exception propagates up and terminates the program.

Instead, you must clear out the bad input in your input stream by calling something like s.nextLine().

catch (Exception e) {
   s.nextLine();  // Consume the current line of bad input
   System.out.println("Write True or False");
   boolean c = s.nextBoolean();
}

At this point, the bad input has been consumed, and the user can type in "True" which is consumed by the s.nextBoolean() call:

F R E D \n T r u e \n

AJNeufeld
  • 8,231
  • 1
  • 22
  • 40