-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessTheNumber4.java
More file actions
65 lines (52 loc) · 1.74 KB
/
Copy pathGuessTheNumber4.java
File metadata and controls
65 lines (52 loc) · 1.74 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package Java;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber4 {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int number = random.nextInt(1, 10);
int limit = 5;
int guess;
System.out.println("Guess 0 - 9");
while (true) {
try {
System.out.print("Guess: ");
guess = scanner.nextInt();
if (guess < 0 || guess > 9) {
throw new Exception();
}
} catch (InputMismatchException ime) {
scanner.nextLine();
System.out.println("That's not a number");
continue;
} catch (Exception e) {
scanner.nextLine();
System.out.println("Guess 0 to 9 only");
continue;
}
if (guess == number) {
System.out.println("Correct!");
scanner.close();
break;
} else {
limit--;
if (limit == 0) {
System.out.println("You're out of guesses");
System.out.println("The number is " + number);
break;
} else if (limit == 1) {
System.out.println("1 guess left");
} else {
System.out.println(limit + " guesses left");
}
if (guess > number) {
System.out.println("Lower!");
} else {
System.err.println("Higher!");
}
}
}
}
}