1
Scanner choice = new Scanner(System.in);
    while(!choice.hasNextInt()) {
        System.out.println("Invalid input");
        choice.next();
    }

    // Carry out appropriate method relating to user choice
    boolean done = false; // Loop is not finished
    while (!done) {
        int i = choice.nextInt(); // Save the user's choice as int i
        /*
         * A switch statement here would probably be more elegant but this works too
         * Problem: If the user inputs a non-integer number e.g. 2.3 the program explodes :(
         */
        if (i == 1) {
            newGame(); // Call newGame method
        } else if (i == 2) {
            playGame(); // Call playGame method
        } else if (i == 3) {
            viewResults(); // Call viewResults method
        } else if (i == 4) {
            done = true; // If user quits, the loop is done
            quitGame(); // Call quitGame method
        } else { 
            System.out.println("Invalid input");
        }
    }

The only valid input for this needs to be the numbers 1, 2, 3 and 4. If I enter a string it doesn't accept it. If i enter a number larger than 4 it doesn't accept it. However if I was to enter 2.3 or something the program crashes. I can't see what it causing this as 2.3 is not an integer and I don't know how it gets past the hasNextInt() method in Scanner. Anyone shed some light?

Charles
  • 50,943
  • 13
  • 104
  • 142
Lightspeed
  • 21
  • 1
  • 4

2 Answers2

1

For input 2., first int is 2, so playGame() is executed but done is still false so because of the while(!done) loop choice.nextInt() is called again on . which is not an int.

Hence the exception.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0

You only check that choice.hasNextInt() for the first input. The second time round it is not checked. Move the check into the while loop so that it looks like this:

boolean done = false;
while (!done) {
    while(!choice.hasNextInt()) {
        System.out.println("Invalid input");
        choice.nextLine(); // drop entire line, not just next token
    }
    int i = choice.nextInt();
    // ...
}
tom
  • 21,844
  • 6
  • 43
  • 36