Slerig
Slerig

Reputation: 95

Getting an infinite loop in Java due to error miss-handling. How can I fix this?

This is my loop. It repeats endlessly if a non-int is entered. From what I can see, it seems like the exception isn't cleared on the next run of the loop. Or because it takes the previous input and assigns it to menuChoice. How can I fix this?

while(!console.hasNextInt())
{
    try {
        menuChoice = console.nextInt();
    } catch(InputMismatchException e) {
        System.out.println("The selection you made is invalid.");
    }
}

Upvotes: 0

Views: 188

Answers (2)

andy
andy

Reputation: 1105

this might be faster because hasNextInt() and nextInt() both try to parse the next token to an int. In this solution the parse is only done once:

while(console.hasNext()){
    try {
        menuChoice = console.nextInt();
    } catch(InputMismatchException e) {
        System.out.println("The selection you made is invalid.");
    } finally {
        //throw away non-ints
        console.next();
    }
}

Upvotes: 0

Chris
Chris

Reputation: 23179

don't check for an int in the while loop, check for any input token:

while(console.hasNext()){
  if(console.hasNextInt()){
   try {
        menuChoice = console.nextInt();
    } catch(InputMismatchException e) {
        System.out.println("The selection you made is invalid.");
    }
  }else{
     //throw away non-ints
       console.next();
  }

}

Upvotes: 3

Related Questions