public class Guess { public static void main(String[] args) throws IOException { int upper = 100; int lower = 1; int guess; char ans = 'N'; System.out.println("Think of a number between 1 and 100"); while (ans != 'Y') { guess = lower + (upper - lower) / 2; System.out.println("Is your number" + guess); System.out.println("Answer One of "); System.out.println("Y(es)"); System.out.println("B(igger)"); System.out.println("S(maller)"); System.out.print("?"); do { ans = (char) System.in.read(); } while (ans == '\n'); if (ans == 'B') { lower = guess; } if (ans == 'S') { upper = guess; } }
System.out.println("I guessed it!!"); } }
If you type this program in then it should guess any number between 1 and 100 in the minimum number of guesses.
The only part of the program not explained even a little bit is the use of
throws java.io.IOException
and the
import java.io.IOException;
at the start which is all to do with picking up run time errors and it is something we will have to return to.
I also have to admit that this program would be easier to write using strings, arrays and classes, but more of all of these in the next chapter. It is a fact that the more Java you know the easier things are to write.
You should also notice that this simple program was in fact quite difficult to implement because of all of the tiny details that you needed to know to make it work.
Learning any programming language is a lot like this. The broad picture is always the same but small details like != meaning not equal and /n meaning the return key vary and you have to get everything 100% right for anything to work.
Play with this example and see if you can improve on it.
Try writing a program which accepts any two numbers and displays their sum. Next try to extend this to any number of numbers with the last number indicated by a zero.