Lecture 10: Building A Program With Loops


In class today I'm going to build from scratch a simple guessing game program. This will allow us to go through the process of designing a program, step by step. This program will also give us a chance to try out the different types of loops (while, for) and see what's actually happening with the variables as the program runs.

The first thing that you need to do for today's lab is get Eclipse up and running. Don't worry about getting your workspace in the right place or finding your files that you were previously working on. For the purposes of today's lecture you'd just want to have any Eclipse file open so you can try putting in code and getting it to run. All code today will come from the examples given in today's notes (and anything else you come up with).

Once you have the Eclipse program opened, you'll need some project and some file stored in that project so you can type in code. You do that by asking to create a new project under the File menu header. You then ask to create a new file by using the same option (just choosing "File" instead of "Project" as the last option). For today's exercises you can use any names you like (potential names might Loops and LoopDemo for the project and file names, respectively).

Quick aside: Don't try this right now, but it's possible to switch the workspace where your files are stored. You'd do this using the "Switch Workspace" option as shown below.

Once you select that option, you'd simply click the Browse button to navigate to whatever fold you want to have contain your code (or to whatever folder already does contain some of your code). Also, you can reset Eclipse's preferences so that it will always ask you what workspace you want to use. This is done by choosing the Preferences option under the Edit menu header. Then you'll get a panel of preference options. From there you'd choose to have Eclipse always ask for a workspace location, like so:

Getting Started Coding

Now, the real purpose of today's lecture is to try making a simple program with loops, and explain each part of it along the way. To do this, we'll be putting the code inside the file (possibly named LoopDemo) that you created. Our code for the example will be going inside of the main method. This is the little stub of code that Eclipse often generates for you.

  public static void main(String[] args){
    // your code goes here
  }

So, all of the code today will go between the curly braces, in the area where the text above says "your code goes here". The task for today's lecture is to make a guessing game. The user (of the program) is supposed to think of some integer number. The program will then guess that number. It will do so by repeatedly asking the user yes/no questions.

Before writing any code, it's usually a good idea to first think of the algorithm for solving the problem at hand. An algorithm is the actual step-by-step process used to do something. A program is simply something that will execute the algorithm that we have designed. This is an important distinction between these two terms (algorithm vs. program). So the first thing that we'll do is figure out the step-by-step process that we would use to guess the number if the task were up to us.

Here's one such example process: Start by guessing 0. Ask the user if their number is 0. If not, repeat the process by guessing 1. If it's not 1, repeat by guessing 2, 3, 4, etc. We'll continue on until we finally guess the number. This does make the simplification that we're assuming the user to be thinking of an integer >= 0. This may not be the case, but we'll assume that to begin with so that we can get some program working.

Now that we have a step-by-step process, there are 2 things to consider so that we can put that into code: what information did I have to remember while running my "algorithm" and how can I implement the steps of my algorithm in code. Now is a time when we can try putting in comments to keep track of what we're trying to do. Again, comments are just notes put in the code to be viewed by humans. The computer will ignore them.

First I'll put in comments about what I need to remember. First, I need to remember the number that represents my current guess at what the user is thinking of. Since this has to be an integer number, an int variable will do just fine. I'll put that in later, but for right now I'll just put a comment telling myself that's what I want. What else? Well, I'm having to ask the user a yes or no question each iteration through my algorithm. So, I'll probably want a variable to store their response to my last question. I'll choose to store that information in a String variable.

Now the only part left is actually running the steps of my algorithm. Since each step is almost the same - I just increase the number by 1 each time - a loop is probably the way to go. I'll think of this in terms of a while loop to start out, just because that's the simplest type of loop. In the example code below, I've put in the steps of my algorithm - but just as comments.

The comments above about my algorithm's loop are written as pseudo-code. Pseudo-code doesn't have any definite rules for how its written. It's supposed to be something that's "almost code" but you ignore details like the exact syntax that a language like Java wants you to use for each line of code. In my pseudo-code above I'm getting across the idea of what my code should do, but I haven't worried about writing actual code and getting that to work. Finally, I've also added one step at the end to indicate to the user when I think I've found their secret number.

We've now completed the first step of figuring out exactly what we want our program to do. That's the most important part. The rest is just learning the tricks of the Java programming language. To get started with that, I'll again start with the easiest part: declaring my variables. I decided before that I needed one int and one String variable. So I'll declare them at the top of the program right under the comments that I wrote in as a placeholder. I'll leave the comments as a note to myself, or anyone else who reads my code, explaining what I was trying to do. Comments may not seem very important here, but trust me, they can be quite helpful.

Now that I've created some variables, I can put in the code for my loop. Each time through the loop I need to ask the user if my current guess happens to be their secret number. I'll just do that with a call of System.out.println(). Inside the paramater that I give to the println method I'll include a couple of string literals, "Is this your number" and "(yes/no)? ". Between those string literals I'll insert my guess for the user's number. Remember that because I've got String's involved, the + operator will turn the operands on both sides of it into String's. So, my variable guess gets promoted to being a String and everything gets concatenated together before it's printed out to the console window.

In addition, I'll also have to read in the user's yes/no response. I can do this with a call to Keyboard.readString(). This will give me the String of the user's response, and I'll set my response variable equal to that using the "=" ooperator. (Remember, just a single equals sign for assignment, =, but a double equals sign would be used for comparison, like: ==). Here's my code below:

Two more details to handle: first, inside the comparison test of my while loop I'm going to continue if the user responded with "no". Here I'm using the equals method to do this because the object in question is a String object instead of a primitive data type. Now, aside from the Java code there's one extra issue: getting the Keyboard methods to work. If the cs1.jar file hasn't been added yet, you should have some red underlining part of your code. This indicates that you have an error and your code won't run. There's also red box over to the left of that line of code. You can hover over that box to find what the error is. You can also click on the box to get some suggestions from the compiler (what interprets your code) as to how you can correct the problem. As for the cs1.jar file, you can actually add that to any project quickly and easily. Just right-click on the project folder, then move to the bottom of the menu and select the properties option.

Once you've chosen that option, you should have a window like the one below. In that window click the "Libraries" tab highlighted in blue below.

Finally, just click the "Add External JARs" button, highlighted in blue below. Once you've clicked on that you'll have to browse to wherever the cs1.jar file was saved on your computer in order to select it and add it.

With that file added in, our code should be set and ready to go. Running it should give us the simple guessing game program. In class, I'll also be updating it to do slightly more complex things, little bit by little bit.

Bounds on the Secret Number

Our current guessing game assumes that we're trying to guess a number > 0. This may not be the right assumption to make. So, we can first ask the user to give us a number lower than their secret number, and a number higher than their secret number. Now we can start one spot above the lower number and count up until we get to their secret number OR when we reach their upper-bounding number. To get the "higher" and the "lower" numbers I'll just need to ask the user. This is done with the two-line combination of System.out.println(); and int num = Keyboard.readInt(); that we're seeing so much of. Here's the new code:

Note that there's also a different in my while loop. In the condition check that it performs before each iteration I'm now testing two things: if the user still responded with "no" AND if my guess number has now gotten as large as the upper bound given to me by the user. I'm joining these two statements using the logical and operator: &&. Don't worry too much about this operator for now. The big thing is just understanding how the loop is working.

Code files: Loop1.java Loop2.java Loop3.java Loop4.java Loop5.java Loop6.java