-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGuessingGame.java
74 lines (56 loc) · 2.45 KB
/
GuessingGame.java
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
import java.util.Scanner;
import java.util.Arrays;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
this.instructions(lowerLimit, upperLimit);
// int startingValue = average(upperLimit, lowerLimit);
// int[] guesses = new int[howManyTimesHalvable(upperLimit - lowerLimit)];
// guesses[0] = startingValue;
// int average = 0;
//int i = -1;
while(true){
int average = average(lowerLimit, upperLimit);
if (isGreaterThan(average)) {
lowerLimit = average + 1;
} else {
upperLimit = average;
}
if(lowerLimit == upperLimit) {
System.out.println("The number you're thinking of is " + lowerLimit + ".");
break;
}
}
// System.out.println("The number you're thinking of is "+ lowerLimit);
//System.out.println("The number you're thinking about is " + lowerLimit + ".");
// write the guessing logic here
}
// implement here the methods isGreaterThan and average
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
public boolean isGreaterThan(int value) {
String response = "";
System.out.println("Is your number greater than " + value + "? (y/n)");
response = reader.nextLine();
return response.equals("y");
}
public int average(int firstNumber, int secondNumber) {
return (firstNumber + secondNumber)/2;
}
}