Lab 5 In-Class: Exploring Data Representation & Writing Classes

Lab Objectives

  • Experience the problem of overflow; gain an understanding of why it happens and how to recognize it.
  • Gain more experience with casting and widening data conversions.
  • Gain experience writing a class and using the class in a client program.
  • Learn the basics of using graphics in an application (rather than an applet).
  • Experience using graphical objects defined in separate classes.

Log onto the Linux system and create a lab5 subdirectory of your cs120/Labs directory for today's work. As usual, you will need to have three windows open: an xterm, Eclipse, and Firefox.

What is your age in seconds?

The file Age.java contains the skeleton of a Java application that will take as input a person's age in years, months, and days and then compute and print the age in seconds.
  1. Complete the program as follows:

    Test your program. For example, a person who is 18 years, 3 months, and 21 days old has lived 577,238,400 seconds (under the assumptions of the program). A person who is 21 years, 0 months, and 0 days has lived 662,256,000 seconds.

  2. How many seconds has a person who is 68 years, 6 months, and 12 days old lived? Run your program to find out.

    You should have gotten a strange answer to the last question! Why did your program produce such an answer? Hint: Java uses a 32-bit two's complement representation for type int. In pre-lab you computed the largest int value that Java can represent (it is also in the textbook on page 72). Now look at the other ages in seconds you have computed, e.g., 21 years. 68 years is a little over triple that value; is this consistent with your strange answer? (No need to write this answer.)

  3. Fix your program as follows:

    Test the program again and make sure it works. A person who has lived 68 years, 6 months, and 12 days is 2,161,036,800 seconds old. Also try 99 years, 9 months, and 9 days and make sure the answer makes sense.

  4. Print your final program.

Writing Classes: The Account Class

Program Account.java contains the Account class from the pre-lab and pages 178-179 from the textbook.

  1. Fill in the declaration/initialization of the constant for the $10.00 fee (after the RATE constant - below the comment), your definitions for methods chargeFee and setName. Make sure your class has no compile-time errors (no red x's).

  2. Program ManageAccounts.java contains the shell of the program from the prelab that uses the Account class to create and manipulate bank accounts. Add code as indicated by the comments. Note that this program asks you to use getBalance to print the balance in two places that were not in the prelab and it has added some interactive input (and asks you to add statements to deposit and withdraw amounts entered). Run your program and make sure it works.

  3. Updating the documentation: It is very important that methods in a class be well documented so that programmers understand what they do and can use them properly. Every method should have documentation just before the method that describes what the method does, the parameters the method takes, and any values the method returns. Eclipse will automatically generate javadoc style documentation for methods. It produces a list of parameters and an @return statement. The programmer must fill in the following: Read through the Account class and you will see that the constructor, the deposit, addInterest, and chargeFee methods already have documentation. Do the following to document the withdraw method:

    1. Place your cursor on the header for the withdraw method (anywhere on the header but be sure to be on the code). Then, from the menu, select Source, Generate Element Comment.
    2. Eclipse should have generated javadoc comments that look as follows:
             /**
             * @param amount
             * @return
             */
      
    3. Add a line describing what the withdraw method does just above the @param tag (see the deposit documentation). Press enter so you have a blank line in the documentation between the description and the @param line.
    4. Beside the parameter amount (or on the next line - formatting will put this on the next line no matter where you put it) write a brief description of the role of the parameter amount (again, see deposit).
    5. Beside @return write a description of what is returned by the method.
    6. Press SHIFT-CTRL-F to format.

  4. Repeat the above steps to add documentation to getBalance and setName. You can use the descriptions in the textbook if you wish (or in pre-lab).

  5. Although chargeFee returns the new balance, your ManageAccounts program currently throws that value away. Modify ManageAccounts so that each time it calls chargeFee it stores the returned balance in a variable (you'll have to declare a new one). After each call to chargeFee, add a print statement that prints the stored value of the new balance (appropriately labeled).

  6. Real bank accounts have many more attributes than the three in this simple Account class. For example, a record of each transaction would be associated with each account. That is too complicated for us but we can keep track of the number of transactions. To do this add the following to the Account class:
    1. Add an instance variable named numTransactions of type int. Remember that we make instance variables private.
    2. In the constructor, initialize numTransactions to 0. (NOTE: Java automatically initializes instance variables to 0 but it is generally a good idea to explicitly assign initial values.)
    3. In the deposit and withdraw methods increment numTransactions.
    4. In the toString method modify the string returned to include the number of transactions.
    5. Classes often have accessor methods for each attribute (see page 171 of the text). These methods are often called "get" methods or "getters." All they do is return the value of the attribute so the client program can use it in some way (print it or use it in a calculation for example). The getBalance method is an example of an accessor method. We need to add a getTransactions accessor method to the Account class (note this goes in Account.java). It will be similar to getBalance except it will return the number of transactions. Think about what the return type for the method needs to be. Be sure to generate javadoc comments for the method.
    6. Add a print statement at the end of the ManageAccounts program to print out the number of transactions for each account (use your accessor method). NOTE: Add this even though you are already printing the complete account information - this time you should print just the number of transactions using getTransactions.

  7. You should have noticed that accessor (getter) methods are very straightforward to write. In fact, Eclipse can automatically generate both accessor methods (getters) and mutator methods (setters). An example of a setter is setName - it sets the name attribute to the new name that is passed in as a parameter. Have Eclipse generate an accessor method getName() as follows:
    1. From the menu, choose Source, Generate Getters and Setters.
    2. Explore this window by clicking on the small arrow beside acctNumber - you will see options of a getAcctNumber and a setAcctNumber. If you click on balance you will only see the option of a setBalance because the class already has a getBalance. Similarly if you click on name you will only see the option of getName.
    3. getName is the one we want so click on the box to select it.
    4. Now click okay.
    5. You should see the complete code for the method plus the javadoc. Add a line describing the method to the javadoc and add a description of what is returned to the @return statement.

  8. Modify the last print statements (that printed the number of transactions) to also print the name of the account owner using the getName method in your print statement.

  9. Run your program to test it then print Account.java and ManageAccounts.java.

Writing Classes: Graphical Objects

In this exercise you will complete a graphical application that contains three snowmen holding balloons. Both the snowmen and the balloons will be graphical objects defined in separate classes.
  1. Download the following files to your lab5 directory. Open them in Eclipse and make sure that you understand the code. Specific observations are provided for each file:
    1. The file Snowman.java contains the class that defines a graphical snowman. This is the same as the snowman on pages 100-101 except the code for the snowman has been encapsulated in a class. The main difference is that the values for positioning the snowman are constants in the program on page 100 (MID is how far over the middle of the snowman is on the page and TOP is how far down the top of the head is) but instance variables in the class.
      • The values for mid and top are specified when the object is instantiated (using the constructor). Currently the contructor does not have any JavaDoc comments indicating the role of its parameters. Use Eclipse to generate the comments for the constructor and fill in a description for each of the parameters.

    2. The file WinterPanel.java customizes a JPanel to include a snowman, the sun and some steps. Observe the following:
      • This class extends a JPanel much in the same way previous classes have extended JApplet. This means that a WinterPanel is a specific kind of JPanel; it does everything that a JPanel does plus a little more.
      • After directly drawing a sun and some steps, this class instantiates a Snowman object (note that the arguments are position of the middle and top of the snowman). It then invokes the draw method of the Snowman class to draw the snowman.

    3. Finally, the file WinterScene.java is actually an application that makes use of these classes. It creates a JFrame and a WinterPanel, add the WinterPanel to the Frame and displays the JFrame. Notice that this program is the only one that contains a main method.

  2. Run WinterScene.java to see what the scene looks like.

  3. Modify WinterPanel.java so that it instantiates and draws two additional snowmen, one positioned on the step to the left of the current snowman and one to the right. Run the program (WinterScene.java) to verify that the snowmen are in the correct positions.

  4. The next example uses a set of classes including a balloon class that defines graphical balloon objects, a panel to draw the balloons and an application that displays the panel in a frame. (Note: this is very similar to the Circle example on pages 186-190)

    1. The file Balloon.java contains a class similar to the Circle class (the accessor and mutator methods are not included). Study the constructor for this class to understand how its parameters are used. Use Eclipse to generate the JavaDoc comments and then fill in a description for each of the parameters.

    2. The file BalloonPanel.java instantiates and draws three objects of type Balloon for the customized JPanel. You should observe that this is very similar to the WinterPanel.

    3. The file BalloonApp.java is an application that puts the BalloonPanel into a Frame and displays it. Run this file as an application. You should note that the "balloons" don't look like balloons (they are just elongated circles with a width that is .9 times the height).

  5. Modify Balloon.java so what is drawn looks like a balloon! To do this modify the draw method by adding a string (a straight line) hanging down from the balloon. The string should be twice as long as the balloon is high. Before adding code, draw a picture and figure out what the starting point and ending point of the line should be. Reexecute BalloonsApp.java to verify that the balloons are drawn correctly.

  6. Go back to the DrawSnowman program and for each snowman instantiate and draw a balloon object so it looks like the snowman is holding the balloon (in either hand - you choose).

  7. Print out Balloon.java and WinterPanel.java to hand in.

Hand In