-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame5.java
More file actions
86 lines (63 loc) · 2.1 KB
/
Copy pathNumberGuessingGame5.java
File metadata and controls
86 lines (63 loc) · 2.1 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package practice;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame5 {
static Scanner scanner = new Scanner(System.in);
static ArrayList<Integer> guesses = new ArrayList<>();
static int guess;
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(10);
int limit = 5;
while (true) {
getGuess();
// Correct
if (guess == number) {
System.out.println("Correct! It's " + number);
break;
}
// Wrong | Out of guesses
limit--;
if (limit == 0) {
System.out.println("Out of guesses! It's " + number);
break;
}
// Clues | Hints
if (guess > number) {
System.out.println("Lower!");
} else {
System.out.println("Higher!");
}
// Reminder of number of guess left
System.out.println((limit > 0) ? limit + " guesses left" : "1 guess left only");
}
scanner.close();
}
private static int getGuess() {
while (true) {
// Checking #1 - Check if the input is a whole number
try {
System.out.print("Guess: ");
guess = scanner.nextInt();
} catch (InputMismatchException ime) {
scanner.nextLine();
System.out.println("Invalid input");
continue;
}
// Checking #2 - Check if the guess is in range
if (guess < 0 || guess > 9) {
System.out.println("Guess 0-9 only");
continue;
}
// Checking #3 - Check if guess is said already
if (guesses.contains(guess)) {
System.out.println("You've already tried " + guess);
continue;
}
guesses.add(guess);
return guess;
}
}
}