0

I have a while loop running in order to make sure the user enters proper information. However, it doesn't go through the loop to ask the user again. For example, if I enter "k" when it is looking for an integer, it will not go through any of the program, instead nothing will be output and the program is stuck. I found a question similar to this problem, however the solution offered still does not work. While before my program would skip the while loop and continue, now it is caught doing nothing for eternity.

while (errorLoop) {
    try { 
        if (kb.hasNextInt()) {
            Player.setBet(kb.nextInt()); 
        } 
    } 
    catch (InputMismatchException e) {
        System.out.println("Please enter a positive number."); 
    } 
    if (Player.getBet() > 0) { 
        errorLoop = false; 
    } 
}
Community
  • 1
  • 1
DJOwen
  • 21
  • 1
  • 7

1 Answers1

1

Your code is not ignoring the try-catch, it simply can't throw InputMismatchException, since before calling kb.nextInt() you make sure that the next input can be parsed as int (by checking that kb.hasNextInt() is true).

You can remove the try-catch :

while (errorLoop) {
    if (kb.hasNextInt()) {
        Player.setBet(kb.nextInt()); 
        if (Player.getBet() > 0) { 
            errorLoop = false; 
        } else {
            kb.nextLine();
            System.out.println("Please enter a positive number."); 
        }
    } else {
        kb.nextLine();
        System.out.println("Please enter a positive number."); 
    }            
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Isnt the second else case redundant? +1 for nice explanation! – user Oct 19 '14 at 18:47
  • @user Changed the logic a bit. Both elses are required. The first handles negative integers. The second handles non-int inputs. In both cases you want to consume the end of the current line, so that the next iteration can try to find an int on the next line. – Eran Oct 19 '14 at 18:52
  • Now i totally agree ;) – user Oct 19 '14 at 19:00
  • Once I took out the second else statement, it worked. Before that it would print "Please enter a positive number" twice. – DJOwen Oct 19 '14 at 19:00
  • @DJOwen Please note that I edited the answer and changed the order of the statements, so I'm not sure which else statement you took out. If you put `kb.nextLine()` in both else statements, you shouldn't be getting the message twice. – Eran Oct 19 '14 at 19:05
  • @Eran I apologize, I had not refreshed the page to see that. The new answer worked perfectly. – DJOwen Oct 19 '14 at 19:13