Java Reference
In-Depth Information
This pseudocode is fairly easy to turn into actual Java code:
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
while (!console.hasNextInt()) {
console.next(); // to discard the input
System.out.println("Not an integer; try again.");
System.out.print("How old are you? ");
}
int age = console.nextInt();
In fact, this is such a common operation that it is worth turning into a static method:
// prompts until a valid number is entered
public static int getInt(Scanner console, String prompt) {
System.out.print(prompt);
while (!console.hasNextInt()) {
console.next(); // to discard the input
System.out.println("Not an integer; try again.");
System.out.print(prompt);
}
return console.nextInt();
}
Using this method, we can rewrite our original code as follows:
Scanner console = new Scanner(System.in);
int age = getInt(console, "How old are you? ");
When you execute this code, the interaction looks like this:
How old are you?
what?
Not an integer; try again.
How old are you?
18.4
Not an integer; try again.
How old are you?
ten
Not an integer; try again.
How old are you?
darn!
Not an integer; try again.
How old are you?
help
Not an integer; try again.
How old are you?
19
Search WWH ::
Custom Search