CymsSoul

Untitled

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