// CS 101 Lab // Debugging exercise // This program is supposed to play the HiLo game with you - // in which you think of a number and the computer guesses it. // Unfortunately, there are a lot of bugs (both compile-time and run-time). // Fix them to get the program to work. Be sure to test all cases. // Hint: there are no bugs in any of the comments or any of the printed text include java.util.*; public class HiLo { // shorthand for System.out.println() public static void p(String s) { System.out.println(s); } // shorthand for System.out.print() (no newline) public void p2(String s) { System.out.print(s); } // wait for user to enter '0' public static int waitForZero(Scanner scan) { int z = scan.nextInt(); while (z != 0) p2("I said zero. Let's try this again: "); z = scan.nextInt(); } // wait for the user to enter 0, 1, or 2 public static int askHiLo(Scanner scan) { p2(" (0=correct, 1=too low, 2=too high) "); int i = scan.nextInt(); while (i < 0 && i > 2) { p2("Please enter 0, 1, or 2: "); int i = scan.nextInt(); } return i; } public static void main (String args[]) { Scanner scan = new Scanner(System.in); p("Let's play Hi-Lo. You think of a number between 1 and 100."); p("I'll guess it in no more than 7 guesses :)"); p2("Enter 0 when you're ready to play: "); waitForZero(scan); p("Here we go...); int guesses = 0; int lo = 1; int hi = 100; bool found = true; while (!found) { int mid = (hi - lo) / 2; guesses++; p2("Is it " + mid + "?"); int answer = askHiLo(scan); if (answer = 1) { // too low lo = mid + 1; } else if (answer == 2) { // too high hi = mid - 1; } else { // correct! (answer == 0) found = true; } if (lo > hi) { p("That's impossible! Cheater! I give up."); return; } } // found it! if (guesses != 1) { p("ACE! Now that wasn't hard at all..."); } else if (guesses < 6) { p("YEAH! It only took me " + guesses + " guesses!"); } else { p("Phew! " + guesses + " guesses - that was tough."); } p("Let's play again soon!"); } }