-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathGuessTheNumber.java
More file actions
38 lines (32 loc) · 1.21 KB
/
Copy pathGuessTheNumber.java
File metadata and controls
38 lines (32 loc) · 1.21 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
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int low = 1;
int high = 100;
int guess;
String response;
System.out.println("Think of a number between 1 and 100.");
System.out.println("I will try to guess it!");
while (low <= high) {
guess = (low + high) / 2;
System.out.println("Is your number " + guess + "?");
System.out.print("Enter 'higher', 'lower', or 'correct': ");
response = scanner.nextLine().toLowerCase();
if (response.equals("correct")) {
System.out.println("Yay! I guessed your number!");
break;
} else if (response.equals("higher")) {
low = guess + 1;
} else if (response.equals("lower")) {
high = guess - 1;
} else {
System.out.println("Please respond with 'higher', 'lower', or 'correct'.");
}
}
if (low > high) {
System.out.println("Hmm, something went wrong. Are you sure you answered correctly?");
}
scanner.close();
}
}