forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRobustGuessNumber.java
More file actions
26 lines (24 loc) · 940 Bytes
/
RobustGuessNumber.java
File metadata and controls
26 lines (24 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
import java.util.InputMismatchException;
public class GuessNumber {
public static void main(String[] args) {
System.out.println("I'm thinking of a number between 1 and 10.");
Scanner kbd = new Scanner(System.in);
int number = 0;
boolean isValidInput = false;
while (!isValidInput) {
try {
System.out.print("Enter an integer: ");
number = kbd.nextInt();
// If nextInt() throws an exception, we won't get here
isValidInput = true;
} catch (InputMismatchException e) {
// This nextLine() consumes the token that
// nextInt() couldn't translate to an int.
String input = kbd.nextLine();
System.out.println(input + " is not an integer.");
System.out.println("Try again.");
}
}
}
}