forked from DarthJDG/NumGuess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumGuess.java
More file actions
66 lines (53 loc) · 1.54 KB
/
NumGuess.java
File metadata and controls
66 lines (53 loc) · 1.54 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NumGuess {
static String name;
static int limit;
static int number;
static int tries;
public static String readLine() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
return reader.readLine();
} catch (IOException e) {
return "";
}
}
public static void main(String[] args) {
System.out.printf("Welcome to NumGuess Java terminal version!\n\n");
System.out.printf("Enter your name: ");
name = readLine();
System.out.printf("\nWelcome %s, enter limit: ", name);
try {
limit = Integer.parseInt(readLine(), 10);
if (limit < 10) limit = 10;
} catch (NumberFormatException e) {
limit = 10;
}
while (true) {
tries = 0;
number = (int) Math.floor(Math.random() * limit) + 1;
System.out.printf("\nGuess my number between 1 and %d!\n", limit);
while (true) {
int guess;
System.out.printf("\nGuess: ");
try {
guess = Integer.parseInt(readLine(), 10);
tries++;
if (guess < number) {
System.out.printf("Too low!");
} else if (guess > number) {
System.out.printf("Too high!");
} else break;
} catch (NumberFormatException e) {
System.out.printf("That's completely wrong!\n");
}
}
System.out.printf("\nWell done %s, you guessed my number from %d tries!\n", name, tries);
System.out.printf("Play again [Y/N]? ");
if (!readLine().toUpperCase().equals("Y")) break;
}
System.out.printf("\nOkay, bye.");
}
}