Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- 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) {
- instructions(lowerLimit, upperLimit);
- while (lowerLimit < upperLimit) {
- if (lowerLimit == upperLimit) {
- System.out.println("The number you're thinking of is " + lowerLimit);
- break;
- }
- else if (isGreaterThan(lowerLimit)) { // yes
- lowerLimit = average(lowerLimit, upperLimit);
- System.out.println(" lowerLimit value is : " + lowerLimit);
- } else { // no
- upperLimit = average(lowerLimit, upperLimit);
- System.out.println(" upperLimit value is : " + lowerLimit);
- }
- }
- }
- 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("");
- }
- // implement here the methods isGreaterThan and average
- //calculates the average of the given values
- public int average(int firstNumber, int secondNumber) {
- int sum = firstNumber + secondNumber;
- int ave = sum / 2;
- return ave;
- }
- public boolean isGreaterThan(int value) {
- System.out.println("Is your number greater than " + value + " ? (y/n)");
- String response = reader.nextLine();
- return response.equalsIgnoreCase("y");
- }
- // 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment