Java Programming   Java Programming
 |Sofia Home | Content Gallery |
Home
Syllabus
Schedule
Lessons
Assignments
Resources

Assignment 5 - Using Selection

The GuessOMatic is a game of skill...if telling the future can be considered a skill. The GuessOMatic will think of a number between 1 and 100. You pay only $ 1*, and, if you guess the number on the first try, you get... 

Double your money back!!!

If you don't guess the number, then the GuessOMatic will tell you whether you were high or low, and give you another chance to make a killing. Of course, since you missed the first time, you won't get the full $ 2, but "only" $1.75. But hey, since you only put in a buck, that means you've almost doubled your investment!

If you miss your second chance the GuessOMatic points you toward the correct answer, extracting a mere  $.25* for the hint and for the wear and tear on this old applet. Don't be discouraged; that means you still made $ .50* more than you paid. At this rate you'll be a millionaire in no time at all. 

* All amounts are virtual amounts, paid in the Zipoid currency. U.S. cash value is 0.

In this homework, you'll build a larger applet that uses selection, along with the Java 1.0 API. The homework covers the material from Lesson 5, so you should have at least read through the material once before getting started, otherwise, you'll find yourself wasting a lot of effort.

To complete the homework you'll have to understand how to:

  • How to write an action() method using the Java 1.0 event model
  • How to write if statements
  • How to write if-else statements
  • How to write nested if statements
  • How to write "ladder-style" if-else-if statements
  • How to write a switch statement
  • How to enable and disable components
  • How to set the keyboard focus to a particular Button or TextField
  • How to create and use the BorderLayout layout manager
  • How to construct and use Panel objects
Before you start this assignment, you should know how to write a simple applet that uses Button, Textfield, TextArea, Label, and Random objects. This includes:
  • Which import statements you need to use
  • How to create each of the specified objects
  • How to create random numbers, given a Random object.
  • How to get information out of a TextField and convert it to an int value.
Back to Top

Step-By-Step Instructions

At each step along the way, you should stop and compile your code. Make sure that the current step works before moving on. For several steps, there is an associated "Help" screen that will show you how to write that section, if you get into a jam. You should be able to write the code without resorting to "Help", but it's nice to have it there in an emergency. Click on the question mark icon to the right of the Step number if you need help for that step.

Step 1 A help icon.

Download the GuessOMatic starter file, GOM.java. Enter your personal information at the top of your source code. Add your name, your class, your Java ID number, and the date. Every program you write should include this information. Once you have done that, compile your program to make sure that everything is OK with the starter file before you continue.

In the starter file, locate Section 1. Here's where you'll add your applet's attributes, or fields. Add each of the fields described here: 

a. Components which will appear at the top of the applet
  • A TextField named theGuess. This will be where the players enter the numbers that they guess. Make the field 10 characters wide.
  • A Label named bankRoll which will contain the amount of "money" that the player has remaining. (All amounts in this game are expressed as Zipoids--a fictional currency which has no redeeming value: social, monetary, or otherwise). Initialize the bankRoll Label so that it displays "100.00 Zipoids"
b. Components which will appear at the bottom of the applet
  • A Button named newPlayer. This button will be used to give a player a fresh start as well as a new bankroll.  Label the button "New Player".
  • A Button named newNumber. This button is used after each game to calculate winnings and to clear the output screen.  Label this button "New Number".
  • A TextField named thePlayer. When the game first starts, or when the newPlayer button is pressed, the player types his or her name in this field. As the game progresses, this field is also used to display how many games have been played. Make thePlayer field 20 characters wide.
c. A component which appears in the center of the applet
  • A TextArea component named theOutput that will be used to display messages from the game as it runs. Use the default TextArea constructor.
d. Non-visible attributes used by the game
  • A String named playerName, initialized to the empty String.
  • An int named theNumber that will be used to hold the random number "guessed" by the game. Initialize this field to 20.
  • A pair of ints named numTries and numGames which will be used to hold the number of times the user has attempted to guess the current secret number and how many games the current user has played. Initialize both to 0.
  • A double named amtRemaining that will hold the amount of the current player's bankroll. Initialize this to 100.0.
  • A Random object which will be used to create the random numbers for each game. Name your object randomizer, and use the default Random constructor to create it.

When you've finished this step, compile your program. If there are any syntax errors, go back and change your source code and recompile. Repeat until your code compiles without any errors.

Step 2 A help icon.

Write the init() method. In Step 2, you'll add each of your user-interface components to your applet to the method located in Section 2. You might want to recompile after completing each task, just to make sure you get it right.

a. Change the layout manager
  • For this applet, switch to to BorderLayout, by using the setLayout() message, and passing a new BorderLayout object as its argument.
b. Construct the "Top" Panel
This Panel object will hold the components at the top of your applet. Here are the steps to follow:
  • Create a local Panel object variable, inside the init() method, using the default Panel constructor. Name your Panel p1.
  • Create a local Label inside the init() method, containing the text "Make your guess :", and add the Label to the Panel p1. Simply use the add() method as you've done previously for applets. You must, however, remember to send the add() message to the Panel p1, and not to the applet.
  • Now, add the fields named theGuess and bankRoll, in that order, to the Panel p1. Again, use the add() method, sending the message to p1.
  • The BorderLayout layout manager uses a different form of the add() message. Now that your applet has a BorderLayout, instead of just saying add(component), you say add("Direction", component), where direction is "North", "South", "East", "West", or "Center". Using this syntax, add the Panel p1 to the top of your applet. Note that in the Java 1.1 API, this method is overloaded to accept add(component, "Direction") as well as the other way around.
c. Construct the "Bottom" Panel
This Panel object will hold the components at the bottom of your applet. Here are the steps to follow:
  • Create a second Panel variable, named p2, to hold the components appearing at the bottom of the screen. Use the default constructor to create the Panel p2.
  • Once the new Panel is created, add the Button newPlayer, the TextField thePlayer, and the Button newNumber to the Panel, in that order. Use the add() message, and send it to the Panel p2. Remember, this version of the add() method only takes a single argument.
  • Now, add your new Panel, with all its components to the bottom of the applet. As with the previous Panel, you'll have to use the two-argument version of add(), and send the message to the applet itself.
d. Complete the init() Method
There are three things left to be done inside the init() method. You'll need to add some spacing to the sides of the applet, you'll need to add the "output" area to the center of the applet, and you'll need "press the start button" to get your applet moving.

Here's how you complete each of these tasks.

  • Create two "dummy" Labels which contain two spaces each, and add them to the left and right sides of your applet, using the two argument version of add().
  • Add the TextArea component, theOutput, to the center of your applet, using the two-argument version of add().
  • At the end of your init() method, call the method named newPlayer().
e. Compile and Test
Compile your code and make sure you don't have any errors. If any syntax errors occur, then edit the source code to remove the mistake, and recompile. Repeat until your program compiles without errors.

Create an HTML file using the code below, and test your program in appletviewer.

Click here to see the applet as it should look at this point.
<applet code=GOM.class width=375 height=250>
</applet>

Step 3 A help icon.

Write the code for the method named newPlayer(). This method is located in Section 3 of your program and is called whenever the player wants to get a "fresh" start, or when a different player wants to play the game. 

Here are the specifications for the newPlayer() method. 

a. Ask the user to "sign in" to the game:
  • On the first line of the method, clear the TextArea object named theOutput by sending it the setText() message, passing an empty String as the argument.
  • Next, tell the player to enter their name and press Enter to begin playing. Use the TextArea appendText() method to place your message in theOutput.
b. Disable all components except for thePlayer:
  • This includes the following fields: theOutput, theGuess, newPlayer, and newNumber (Because you are using Java 1.0, you'll use the disable() method instead of setEnabled(false)). Note: Some versions of the Microsoft JVM have difficulty displaying a TextArea after it is disabled. If this occurs, you may leave theOutput enabled.
  • Set the background color of the field theGuess to white.
c. Activate and clear the field named thePlayer:
  • Enable the field by sending it the enable() message.
  • Clear the field by sending it the setText() message, passing an empty String as the argument.
d. Focus the user's attention on thePlayer field:
  • Set the keyboard focus to the field.
  • Set the background color of the field to yellow, using the setBackground() method, and passing Color.yellow as the argument. This way when the game comes up the player will automatically look at this field.

Now compile again, get out any annoying syntax errors that may have crept in, and run it.

Click here to see how the applet should look and behave at this point. The text field at the bottom should be yellow and the cursor should be blinking, allowing you to type your name.  All other fields should be disabled.

Step 4 A help icon.

Write the method named action(). You'll use the Java 1.0  action() method to handle the events generated by the Buttons and TextFields on your applet. The Help page for this step has more information on the action() method. You'll find the action() method in Section 4 of your source code.

Because your applet has several different Buttons and TextFields, you'll need to use selection to determine which component generated each event, and act accordingly. Your action() method will perform different statements depending upon the situation. You will need a "ladder-style" if-else-if-else structure to handle this. The Help page for this step has more information on using the if, if-else, and if-else-if-else statements.

Because this is a Java 1.0 action method, you'll test the value of the field ev.target in each of your if statements. Here are the four different situations you need to handle:

  • Situation A: If the ev.target field is equal to the Button named newPlayer, then call the method newPlayer().
  • Situation B: If the ev.target field is equal to the TextField named thePlayer, then call the method addPlayer().
  • Situation C: If the ev.target field is equal to the Button named newNumber, then:
    • Call the method newGame()
    • Send the user to the field named theGuess. To do this you should:
    • Enable the field
    • Place the cursor on the field
    • Set the background of the field to yellow
  • Situation D: If the ev.target field is equal to the TextField named theGuess, then call the method newGuess().

When you have finished the action() method, compile and fix any syntax errors. Then run your program in appletviewer. You should be able to enter your name into the TextField thePlayer and press Enter. When you do, you should see a message in the console window, letting you know that the addPlayer() method was called. If you run the applet in your Web browser, the notification messages will appear in the Java Console, not in a DOS window.

You can see how the applet should behave in a Web browser by clicking this link.

You can't test out the other methods just yet, because all of the Buttons are disabled. We'll remedy that in the next step when we tackle the addPlayer() method.

Step 5 A help icon.

Write the code for the method named addPlayer(). This method will be called when the player has finished entering their name, and has pressed ENTER. When this occurs, you want to carry out the following steps.

  • Retrieve the text from thePlayer TextField, and store in the String field playerName. After this, check to see if playerName is "" [empty]. (You'll have to use the equals() method to do this.) 
If playerName is empty, then:
  • Print an error message to theOutput. Use the appendText() method to print your message. Tell the user that they need to enter a name to play.
If playerName is not empty, then:
  • Set the amount remaining to 100, (the amtRemaining field) and set the number of games played (the numGames field) to 0.
  • Call the newGame() method, followed by the updateScore() method.
  • Disable the field thePlayer and set its background color to white.
  • Enable the fields newPlayer, newNumber, and theGuess.
  • Set the keyboard focus to the field called theGuess. To draw the player's attention to theGuess, set its background color to yellow.

Once you've finished, compile and fix your syntax errors. Then, run your program in appletviewer. Now you should be able to click on all the buttons and see that your methods are being correctly called.

Click here to see the applet running.

Step 6 A help icon.

Finish coding the newGame() method. This is a private method that takes no arguments and returns no values. You'll find this method in Section 6 of the starter file. 

Inside the method, add the following code:

  • Increment the number of games played. [This is the numGames field.] Calculate a new random number between 0 and 100, using your Random field, and store it in the field named theNumber.  Set the number of tries [the numTries field] to 0. Call the displayInstructions() method.
  • Subtract 1 Zipoid from the amount remaining, [ the amount wagered ] and call updateScore().

Compile and run your program.

You can click here to see what the program should look like at this stage.

Step 7

Write the code for the method named displayInstructions(). This method is called whenever a new game is started. It is located in Section 7 of your starter file, and it is called from the newGame() method that you just finished. For this step, start by running the sample program at the top of this page. Enter your name, press ENTER, and then make note of the instructions that are displayed. Use the appendText() method to display the instructions in the TextArea named theOutput.

When you're finished, compile to catch any syntax errors. Then run the program to make sure that the instructions display as they should.

You can click here to see how the program should work at this point.

Step 8

Write the code for the method named updateScore(). This method is called whenever a new game is started. You should do two things in this method:

Display the user's name and game number in the field named thePlayer.

    1. Use the setText() method to update thePlayer field
    2. Combine the user's name [playerName] and the game number [numGames] using String concatenation.

Set the text in the bankRoll Label so that it displays the amount of money still remaining in the user's account.

    1. Use the setText() method to update the bankRoll field.
    2. Combine the amtRemaining field along with the words " Zipoids" using String concatenation.

When you're finished, compile the code and fix any syntax errors.

Step 9 A help icon.

Write the code for the method named newGuess(). This method is called every time the player makes a new guess. The method converts the player's input into an integer and then compares that integer to the number generated by the computer. If the two numbers are identical, then the gameWon() method is called. If not, then the method prints a helpful message letting the player know whether their guess was too high or too low.  Here are the steps to carry out in this method:

Retrieve the text from the field named theGuess and convert the text to an int. You'll need two local variables:  A String called curStr to hold the text retrieved from the field theGuess An int named curGuess, used to hold the guess entered by the user. Use the Integer.parseInt() method to convert curStr to curGuess. Increment the number of guesses the user has made. This is stored in the int field named numTries.  Print the number of guesses and the value of curGuess to theOutput. Test the curGuess variable to see if it is the same as the value "guessed" by the computer. (This value is stored in the field named theNumber). If the user's guess is the same, then call the method gameWon(). If the user's guess is not the same as the value guessed by the computer:

    1. Print a message telling the user to try a higher or lower number, depending upon whether the player's guess was too high or too low. Set the keyboard focus to the field named theGuess Set the background color of theGuess to yellow
    2. Select all of the text contained in the theGuess TextField.

    Stop, compile and test.

    Click here to see how the applet should look and behave at this point. You should be able to enter your name, hit enter and have theGuess field turn yellow and be ready to recieve your first guess. Type in a few guesses. Your applet should correctly identify then as too high or too low.

Step 10 A help icon.

Write the code for the method named gameWon(). This method is called whenever the player selects the correct number. In this method you'll need to calculate and display the player's winnings, and then get set up for the next game. Here are the steps to follow:

  • Print "******* WINNER ********" on theOutput console.
  • Use setText() instead of appendText() so that the previous text is erased.
  • Print the amount wagered, (always 1 Zipoid), and the number of tries [numTries].
  • Use appendText() and use the newline escape sequence '\n' so that each item appears on a separate line.
  • Calculate the amount the user has won by using the field numTries, and a switch statement.  If numTries is 1 then the amount won is 2.00 Zipoids; if numTries is 2, then the amount won is 1.75 Zipoids, and so forth.  If the user makes 9 or more tries, the amount won is zero. 
  • Store the amount won in a local double variable named curWinnings.
  • Print the amount won to output.
  • Add the current winnings to the amount remaining. [You already subtracted the amount wagered inside the newGame() method.]
  • Store the result of this calculation back in the variable amtRemaining.
  • Print the player's name and the amtRemaining to output.
  • Instruct the player to press the New Number button to continue.
  • Call the updateScore() method.
  • Clear theGuess, set its background white, disable it, and set the focus to the New Number button.

Compile and test your program.

Your program should now look and act like the sample program at the top of the page.

As the last step, go through your code and remove [or comment out] all of the System.out.println() statements that were added as stubs.

Finishing Up

Post your applet. Once you've tested your applet locally, add it to the Assignment 5 HTML file on your Web site.

 

Back to Top