-1

I am making a basic application where it trains your math skills. I have this code:

while (true)
        {
            try
            {
                int userAnswer;
                System.out.println("Type quit to exit to the menu!");
                int randInt = r.nextInt(num2);
                System.out.println(num1 + " + " + randInt + " =");
                userAnswer = in.nextInt();
                if(userAnswer == num1 + randInt) System.out.println("Correct!");
                else System.out.println("Wrong!");
                break;
            }
            catch(Exception e)
            {

            }
        }

When someone prints out a d or something in the answer, the try catch goes. But, then it goes to the while loop and repeatedly spams Type quit to exit to the menu and then something like 1 + 2 = infinitely... I think I know what's wrong, userAnswer has been assigned already as something that throws an exception that goes to the catch and it just keeps printing those and goes to the catch and goes back because userAnswer is already assigned. I think this is what is happening, I could be wrong. Please help!

EDIT: I forgot to make this clear, but I want the question to be re-printed again, exiting out of the loop goes to a menu where you can't get the question back, I want it to redo what's in the try catch...

Zach
  • 19
  • 3
  • Possible duplicate of [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – azurefrog Oct 24 '15 at 14:42
  • @azurefrog Why do you think that it is a duplicate of this question? – Tom Oct 24 '15 at 15:08
  • @Tom Because the primary symptom in the OP's program is going into an infinite loop, which is being caused by a lack of a `in.nextLine()` call, which leaves every subsequent call to `in.nextInt()` throwing the same exception. – azurefrog Oct 24 '15 at 19:57
  • @Tom If you stick a `in.nextLine()` in the catch block, the program will re-prompt correctly when the user enters `d`, as per the OP's original use-case. – azurefrog Oct 24 '15 at 19:58
  • @azurefrog Ok, I ask again: Why do you think it is a duplicate of your question? You may mean [this question](http://stackoverflow.com/questions/3572160/how-to-handle-invalid-input-using-scanner-and-try-catch-currently-have-an-infin), but the one you've linked is about something different. – Tom Oct 24 '15 at 20:24
  • @Zach *"I want it to redo what's in the try catch"* So that's why you accepted an answer where it does something you said you won't do? – Tom Oct 25 '15 at 18:28

5 Answers5

0

You should never catch an Exception without handling it.

catch(Exception e)
{
    System.out.println("An error has occured");
    break;
}

This should stop your program from looping infinitely if an Exception occurs.

Yassin Hajaj
  • 20,020
  • 9
  • 41
  • 81
  • e.printStackTrace() may be better since it will give you information such as what the exception is and where it occurred in the code. – Darren Oct 24 '15 at 14:41
  • @Darren Here we know exactly where the exception has occured but you're right. :) – Yassin Hajaj Oct 24 '15 at 14:41
0

If user input comes as letter it will get an exception because you are trying to read(parse) as integer. So your catch clause is in the loop you have to write break in there to go out from loop. Still i will suggest you to getline as string and than compare with your cli commands (quit in your case) than you can try to parse it as an integer and handle loop logic.

Seray Uzgur
  • 117
  • 6
0

You're not breaking the while loop if there is a mismatch

while(true)
{
 try
 {

 }
 catch(InputMisMatchException e)//I suggest you to use the exact exception to avoid others being ignored
 {
  System.out.println("Thank you!");
  break;//breaks the while loop
 }
}
Uma Kanth
  • 5,614
  • 2
  • 16
  • 40
  • I'm sorry I forgot to make this clear, I know I could break the loop, but I want it to play the equation again... That's why I added the loop. I'm not good with the continue word, but could I use that? I'm not entirely certain how to use it and when... – Zach Oct 24 '15 at 20:26
0

Yoy're not breaking the loop in case of Exception occurs.

Add break; statement in the catch block to run your program without going to infinite loop, in case exception occurs.

Alvin3001
  • 109
  • 1
  • 9
0

Since the given answers don't match your requirement I'll solve that "riddle" for you.

I guess what you didn't knew is that the scanner won't read the next token if it doesn't match the expectation. So, if you call in.nextInt() and the next token is not a number, then the scanner will throw an InputMismatchException and keeps the reader position where it is. So if you try it again (due to the loop), then it will throw this exception again. To avoid this you have to consume the erroneous token:

catch (Exception e) {
    // exception handling
    in.next();
}

This will consume the bad token, so in.nextInt() can accept a new token. Also there is no need to add break here.

Mind that in.next() reads only one token, which is delimited by a whitespace. So if the user enters a b c, then your code will throw three exception and therefore generate three different question befor the user can enter a number. You can avoid that by using in.nextLine() instead. But this can lead into another problem: Scanner issue when using nextLine after nextXXX, so pay attention to that :).

Community
  • 1
  • 1
Tom
  • 14,120
  • 16
  • 41
  • 47