CymsSoul

Untitled

Jan 30th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 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 (lowerLimit < upperLimit) {
  17.  
  18. if (lowerLimit == upperLimit) {
  19. System.out.println("The number you're thinking of is " + lowerLimit);
  20. break;
  21. }
  22. else if (isGreaterThan(lowerLimit)) { // yes
  23. lowerLimit = average(lowerLimit, upperLimit);
  24. System.out.println(" lowerLimit value is : " + lowerLimit);
  25. } else { // no
  26. upperLimit = average(lowerLimit, upperLimit);
  27. System.out.println(" upperLimit value is : " + lowerLimit);
  28. }
  29. }
  30. }
  31.  
  32.  
  33. public void instructions(int lowerLimit, int upperLimit) {
  34. int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
  35.  
  36. System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
  37.  
  38. System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
  39. System.out.println("");
  40. System.out.println("Next I'll present you a series of questions. Answer them honestly.");
  41. System.out.println("");
  42. }
  43.  
  44. // implement here the methods isGreaterThan and average
  45. //calculates the average of the given values
  46. public int average(int firstNumber, int secondNumber) {
  47. int sum = firstNumber + secondNumber;
  48. int ave = sum / 2;
  49.  
  50. return ave;
  51. }
  52.  
  53. public boolean isGreaterThan(int value) {
  54. System.out.println("Is your number greater than " + value + " ? (y/n)");
  55. String response = reader.nextLine();
  56. return response.equalsIgnoreCase("y");
  57. }
  58.  
  59. // a helper method:
  60. public static int howManyTimesHalvable(int number) {
  61. // we create a base two logarithm of the given value
  62.  
  63. // Below we swap the base number to base two logarithms!
  64. return (int) (Math.log(number) / Math.log(2)) + 1;
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment