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?