Guessing Game in Java


<<Previous | ToC | Next >>

When you finished your setup in the previous page, you should have a code window (or panel) with something like these five lines in it:

public class Hello {
  public static void main() { // (in StartHere)

    System.out.println("Hello, World!"); /// REPLACE THIS LINE

  } //~main
} //~Hello


We are interested in only one line (shown here in green), the line in the middle. From the three slants '///' to the end of the line is a comment, for people to read but ignored by the computer. You can delete that part of the line, or replace is with anything you like (just keep the first two slants), and Java doesn't care.

The two words in the middle (inside quotes) is a constant, a literal string, the program will print exactly what is inside those quotes. You saw this in English. It works the same way. Except in English you have a choice of quotation marks, but Java insists it be double quotes, as you see here.

The rest of the line, the three words with the two dots separating them, together with the parentheses and the semicolon -- don't forget the semicolon -- are what in English was a single-word Print (or Display or Say) command. For now you can think of it as just another way to spell "Print". Actually it's a subroutine call (all input and output in Java is by subroutines), but we'll see those more later.

You can experiment with printing different things (if you like) before we get into the Guessing Game. You can duplicate the line and make multiple lines of print.

That one (green) line will be where you put all your code today. Just delete the one line and replace it with five or 23 or 99 lines of your own program. Later we will see what the other four lines are for and how to replace them too.
 

Guessing Game

We did the guessing Game in English. This is the second part of "Design in English, then implement in Java" method of writing programs. If you skipped over that part of the introduction, you might consider going back to review how we developed the logic of this program. If you did that and saved your code, use it; otherwise here is my version:
Say 'Hi.'
Say 'We are going to play the Guessing Game.'
Say 'You think of a number between 1 and 99,'
Say 'then I will ask some yes/no questions,'
Say 'then I will tell you your number.'
Say 'Press enter when you think of a number.'
Input answer
Say "OK, let's go"
let top = 100
let bottom = 1
Iterate
  Variable middle = (top+bottom)/2
  round middle
  Say "Is your number less than " middle "? (y/n)"
  Input answer 1
  Say " "
  if answer = "Y" then
  let top = middle
  if answer = "N"
  let bottom = middle
  if bottom+1 = top exit
  Next iteration
Say 'The number you thought of is ' bottom


We are going to replace the single "Hello World" line in our (StartHere) main program with the whole Guessing Game, beginning here and now.

Basically, we will look at each line of this English program, determine which of the Six Things that line is, then choose an appropriate Java representation of the same concept for our Java program. This is also how we wrote the initial English version: we looked at each thing the computer needed to do at that place in the program, and which of the Six Things that was, then wrote (in English) how to say that thing.
 

Output

One-line console output in Java is spelled like this:
System.out.println(string_value);
where the string_value is whatever you want printed. You can concatenate labels and numbers together as in English, but you must start with a value of type String (like something in "double quotes") and the concatenation operator is '+' (don't ask).

You might ask "What are the dots for?" The short answer is, "We'll get to that later." The longer answer is that the people who designed Java thought everything should be "Object-Oriented" even when it's not, so this is explained in my "What You Need to Know" page, here.

Anyway, so your first six lines should be easy. Don't forget the semicolons.
 

Input

In a later game we will look at the (what I call "dangerous") proper Java input methods, but for now, let's do it the easy way. I wrote a fake "System" class spelled "Zystem" with these input methods:
char ch = Zystem.ReadLetter();
int num = Zystem.ReadInt();
If you do this inside the "StartHere" folder, these should work with no extra code. Of course you probably want to (or at least I would suggest you) declare the variables at the front of your method, then leave the type name off the actual subroutine calls. For example, the first Input line would translate to two Java lines:
char ans;
...
ans = Zystem.ReadLetter();


The BlueJ environment requires you to type a return after each input you want your Java program to see separately, but otherwise this should work the same as English.
 

Variables

Kitchen English requires a keyword "let" in front of every assignment, remove that for Java. On the other hand, Java requires a semicolon at the end of every statement.

Java requires that every variable be declared (once) with a line consisting of a type name, followed by the variable name, optionally followed by an initial value, and then maybe more variables of the same type separated by commas, and finally ending in a semicolon. Kitchen English needs a declaration also, but it can figure it out most of the time from some (not all) of the commands, and extras don't hurt.

Data types are important. In Java you can have integer ("int"), float or double, character ("char"), boolean, and String. Later, when we learn about classes and objects, every class name is also a data type. You mostly are not allowed to mix types when comparing or copying variables, or doing math. Mostly.

The English "round" command needs no translation (you can omit it) in Java if you use integer ("int") variables.
 

Iteration

The Java while-loop does what we need. We have more than one line in the part to iterate, so you need the braces:
while (true) {
  ...
  }
The Java early exit is spelled "break;"
 

Conditional

The Java conditional looks a lot like English, except that you must wrap parentheses around the expression being tested, in this case comparing the answer character ans to the constant 'Y' or 'N'. Note that in Kitchen English, quoted strings can be quoted with either apostrophes or double quotes, but Java is strongly typed: apostrophes make a char value, and double quotes make a String value. You cannot compare one to the other.

Also the equality operator in Java is '=='. Important: Be careful not to use a single '=', because Java will not catch your error in some cases, and give you a confusing message in others. I think that was a mistake, but they didn't ask my opinion.

In principle every Java command needs a terminator semicolon ';' but in conditionals and iterators that semicolon is on the following command (the command that gets skipped or repeated), so don't try to put a semicolon at the end of the line (after the parentheses, but before the command you are controlling). The compiler won't warn you (because an empty semicolon is a valid command in Java) and your program won't behave the way you expect.

OK, see if you can make your Java work...

Hmmm...

I seem to have a problem. Let's look more closely at how this works (turn the page).

Next: Using the BlueJ Debugger

<<Previous | ToC | Next >>

2021 October 8