-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.java
More file actions
71 lines (62 loc) · 1.4 KB
/
Copy pathmain.java
File metadata and controls
71 lines (62 loc) · 1.4 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
import java.util.Scanner;
import java.util.Random;
class GuessingGame
{
public static int maxTries = 10;
public enum comparison
{
LESS,
EQUAL,
GREATER
};
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Choose a maximum possible value: ");
int max = reader.nextInt();
Random rand = new Random();
int value = rand.nextInt(1,max);
for (int i = 0; i < maxTries; i++)
{
String str = String.format("Pick a number between 1 and %d", max);
System.out.println(str);
int guess = reader.nextInt();
try {
comparison test = testGuess(guess, value);
switch (test)
{
case LESS:
System.out.println("Too low!");
break;
case GREATER:
System.out.println("Too high!");
break;
case EQUAL:
System.out.println("You win!");
return;
default:
throw new Exception("ERROR 2");
}
}
catch (Exception e) {
System.err.println("ERROR 1" + e.getMessage());
}
}
reader.close();
System.out.println("You lose! Exceeded number of tries!");
return;
}
public static comparison testGuess(int guess, int value) throws Exception
{
if (guess < value) {
return comparison.LESS;
}
else if (guess > value) {
return comparison.GREATER;
}
else if (guess == value) {
return comparison.EQUAL;
}
throw new Exception("Unknown comparison obtained");
}
}