Nested control structures

In this exercise you will get some exposure to nesting control structures. This means putting a control structure such as an if statement, while loop, or do..while inside the code block of another control structure.

"Guess the number" game

Create a new Java program in the usual way. Call it Guess.java.

This program is a guessing game. The computer picks a random number and the user tries to guess it using as few guesses as possible. Here's a preview of the completed program:

I've got a number 0 to 100.
What's your guess?
50
Guess lower.
What's your guess?
25
Guess higher.
What's your guess?
37
Guess lower.
What's your guess?
32
Guess lower.
What's your guess?
29
Got it!

We will first have the computer secretly generate a random number and store it in some variable. You will also have to define another variable that holds the user's most recent guess, so we can compare the two and print out an appropriate message. We will use a do..while loop to repeat the process of asking for a guess and giving them feedback. Here's the basic program structure, which assumes that you put the secret number in a variable called secret:

		//TODO: Determine a secret random number

		int userGuess; //stores the user's most recent guess
		do {
			//TODO: ask for a guess
			//TODO: say whether to guess lower, higher, or if it was correct.
		}while(userGuess != secret); //keep looping back as long as the guess was wrong

Filling in the details

To determine the random secret number, open the Math class documentation and take a look at the random and round methods. One way is to use the random method to get a random double value between 0 and 1, multiply it by 100, then round it using the round method (if you think carefully about this, you will realize that this gives 0 and 100 a lower probability of coming up than the rest of the numbers, but that's fine for this exercise).

You can use if statements inside the loop, just as you would anywhere else. When a control structure is nested inside another (such as an if inside a do..while), the computer still evaluates the line currently being executed by using the current status of the variables. It "thinks locally", evaluating one line at a time when it's running.

One further detail deserves explanation. Notice how the variable userGuess was declared before the main loop. We did this because of something called variable scope. In general, a variable can be used from the line where it was declared, all the way down to the end of the code block in which it was declared. Declaring userGuess where we did allows us to use it for the rest of the main program block. If we had declared it inside the do..while loop, then we only would have been able to use it inside the loop (up to the closing }).

Fill in the rest of the program. Have me check your work, and put your .java source file in folder lab05 on the server when you are done.