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 (seven if you count the blanks) lines in it:

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

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

  } //~main

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 it 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 to the left, 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.

Don't Get Too Creative

We have four programs you already did in English, you are going to translate them to Java as a way to become familiar with the peculiarities of Java. The important thing to remember is, Don't Make Unnecessary Changes. There is a lot of Java to learn, there's no point in taking on more than necessary. After you are comfortable with the conventional way to do Java, you can experiment with your own creativity.

Four programs, you already know how they work, and you will make the same four programs work the same in Java. You already know how to program using the Six Things that encompass all programming in any language. You did it in English starting with PBJ, then you got these same four programs to work in English, and now all you need to change is how to do those same things in Java. The programs already ran in English. The only new thing to learn is Java syntax.

The purpose of this assignment is to become familiar with Java syntax, not to learn new algorithms (program logic), so we give you a program already known to work, all you do is change the spelling to a different language. Oh yes, you also get to learn the Java debugger. Just make it work.

The Java syntax (spelling) for the Six Things was explained a couple pages ago. If your browser has tabs or separate windows, open a new tab (or window) with this link to The Six Things in Java, so you can refer to it as often as needed.

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, (or you can get it from the Done archive, then) use it here. 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
  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.

First, let me remind you that you are working with an early version of this tutorial, and if it's not clear to you what to do, or why the Replit (or BlueJ) compiler doesn't like what you gave it, that's my fault, not yours. Summon a Mentor, and two things will happen:

1. Somebody will come and work with you to get past the problem.

2. I will make the documentation better -- maybe next week, more likely next term. We need your help. Really.

-- or use the "Ask" feature in Zoom.

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. We are doing the same thing now. That's all programming is, figure out which of the Six Things we need here, then spell that in this language.

Actually, the first thing to do is always Design, but we already did that for your English version. Now that English code is the design for your Java. Write the Java to match the English, and your program will work correctly. There are syntactic (spelling) differences, and we'll look at them as they come up, but what the program does will be exactly the same.

While I'm at it, I should mention that most IDEs for Java and other programming languages use a "syntax-directed" code editor, which means that the editor knows what is correct (in this case) Java syntax. Usually it colors different language features differently, and in some cases (like Replit) it will also tell you when you make a mistake -- in Replit, by drawing a red squiggle under the error with a popup message when you roll over it. This should be the same errors the compiler gives you, but a different programmer did it, and they didn't follow the same Design -- where have you heard that before? -- so it may not catch all the errors, or (worse) it may report good code as errors. The editor is only advisory, what matters is the compiler (errors in the Replit black console panel), so if there is a discrepancy, ignore the editor popups.


One-line console output in Java is spelled like this:
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.


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 Java environment requires you to type an Enter key (return) after each input you want your Java program to see separately, and this ReadLetter subroutine passes those Enter keys through and your program will see them -- which usually shows up as duplicated questions. The work-around is to wrap a while-loop (see Iteration below) around the input and discard those characters, like this:
char letter; // declare it outside the loop
while (true) {
  letter = Zystem.ReadLetter();
  if (letter >= ' ') break;} // end of while
Otherwise this should work the same as English.


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 only) 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" and "truncate" commands need no translation (you can omit it) in Java if you use integer ("int") variables.


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;"


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.

Another problem, if you had your players type in whole words instead of single letters, Java String variables do not compare the way you'd expect them to (again, they didn't ask my opinion), and the work-around is messy. I suggest you change your (English) code to read in single characters, then compare to char constants like 'y' and 'n' like my Input example code above.

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...

If your program doesn't run at all (some red text in the Replit console, or a red bar in the BlueJ source code) and you can't figure it out yourself in a minute or two, that's my fault, not yours, summon a Mentor...

-- or use the "Ask" feature in Zoom.


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

Next: Using the Debugger

<<Previous | ToC | Next >>

2023 February 3