Skip to content

Instantly share code, notes, and snippets.

@tomekr
Created November 17, 2011 17:41
Show Gist options
  • Save tomekr/1373857 to your computer and use it in GitHub Desktop.
Save tomekr/1373857 to your computer and use it in GitHub Desktop.
great looking code
// Scanner that will read the integer
final Scanner in = new Scanner(System.in);
int inputInt;
do { // Loop until we have correct input
System.out.print("Specify an integer between 0 and 5: ");
try {
inputInt = in.nextInt(); // Blocks for user input
if (inputInt >= 0 && inputInt <= 5) {
break; // Got valid input, stop looping
} else {
System.out.println("You have not entered a number between 0 and 5. Try again.");
continue; // restart loop, wrong number
}
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
in.next(); // discard non-int input
continue; // restart loop, didn't get an integer input
}
} while (true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment