Advertisement
Guest User

Untitled

a guest
May 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1.  
  2. import java.util.Scanner;
  3.  
  4. public class GuessingGame {
  5.  
  6.     private Scanner reader;
  7.  
  8.     public GuessingGame() {
  9.         // use only this scanner, othervise the tests do not work
  10.         this.reader = new Scanner(System.in);
  11.     }
  12.  
  13.     public void play(int lowerLimit, int upperLimit) {
  14.         instructions(lowerLimit, upperLimit);
  15.  
  16.         while (true) {
  17.  
  18.             System.out.println("Is your number greater than " + average(lowerLimit, upperLimit) + "? (y/n)");
  19.             String yesOrNo = reader.nextLine();
  20.  
  21.             if (lowerLimit == upperLimit) {
  22.                 break;
  23.             } else if (yesOrNo.equals("y")) {
  24.                 lowerLimit = average(lowerLimit, upperLimit) + 1;
  25.             } else {
  26.                 upperLimit = average(lowerLimit, upperLimit);
  27.             }
  28.         }
  29.         System.out.println("The number you're thinking of is " + lowerLimit);
  30.     }
  31.  
  32.     public boolean isGreaterThan(int value) {
  33.         System.out.println("Is your number greater than " + value + "? (y/n)");
  34.         String greaterThan = reader.nextLine();
  35.         return (greaterThan.equals("y"));
  36.     }
  37.  
  38.     public int average(int firstNumber, int secondNumber) {
  39.         return (firstNumber + secondNumber) / 2;
  40.     }
  41.  
  42.     public void instructions(int lowerLimit, int upperLimit) {
  43.         int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
  44.  
  45.         System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
  46.  
  47.         System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
  48.         System.out.println("");
  49.         System.out.println("Next I'll present you a series of questions. Answer them honestly.");
  50.         System.out.println("");
  51.     }
  52.  
  53.     // a helper method:
  54.     public static int howManyTimesHalvable(int number) {
  55.         // we create a base two logarithm  of the given value
  56.  
  57.         // Below we swap the base number to base two logarithms!
  58.         return (int) (Math.log(number) / Math.log(2)) + 1;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement