# Lab 5 In-Class: Exploring Data Representation & Writing 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, emacs, and Mozilla.

### 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:
• declare a conversion constant SECONDS_PER_DAY and in the initialization have the computer do the arithmetic (in other words you shouldn't get out your calculator and figure out how many seconds are in a day -- write the expression so the computer has to do the work)
• define other constants and/or variables as needed
• assume there are 30 days in a month and 365 days in a year
• calculate and print, appropriately labeled, the total number of seconds
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. Given this,

• compute the largest int value that Java can represent -- you'll have to remember the formula for the largest value that can be stored in an N-bit two's complement number, then get out your calculator (or use the calculator under Accessories) to compute it. ***Note both the formula and the value itself, and write them on the program (to turn in) when you print it out.***
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:
• Change the type of ONE (and only one) variable from int to long, which is a 64-bit integer representation. Your program should still work exclusively with integers, not floating point numbers.
• The above change will not completely solve the problem (run your program and see). You need to make sure the expression is computed using the larger data type - a carefully placed cast operator should do the trick!

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.

### A Base Conversion Program

In class we learned an algorithm for converting a base 10 number to another base by repeatedly dividing by the base. Each time a division is performed the remainder and quotient are saved. At each step, the number used in the division is the quotient from the preceding step. The algorithm stops when the quotient is 0. For example to convert the base 10 number 1878 to base 8 you would do the following:
```                            Quotient      Remainder
1878 divided by 8 -->     234             6
234 divided by 8 -->      29             2
29 divided by 8 -->       3             5
3 divided by 8 -->       0             3

```
The number in the new base is the sequence of remainders in reverse order (the last one computed goes first; the first one goes last). In this example, the base 8 answer is 3526 (that is 187810 = 35268). In this exercise you will use this algorithm to write a program that converts a base 10 number to a 4-digit number in another base (you don't know enough programming yet to be able to convert any size number). The base 10 number and the new base (2 - 9) will be input to the program. The start of the program is in the file BaseConvert.java. Open the file in Mozilla, save it to your lab5 subdirectory, then open it in emacs. Modify the program one step at a time as follows:
1. The program will only work correctly for base 10 numbers that fit in 4 digits in the new base. We know that in base 2 the maximum unsigned integer that will fit in 4 bits is 11112 which equals 15 in base 10 (or 24 - 1). In base 8, the maximum number is 77778 which equals 4095 in base 10 (or 84 - 1). In general, the maximum base 10 number that fits in 4 base b digits is b4 - 1. Add an assignment statement to the program to compute this value for the base that is input and assign it to the variable maxNumber. Add a statement that prints out the result (appropriately labeled). Compile and run the program to make sure it is correct so far.

2. Now it is time to add the code to do the conversion. The comments in the program guide you through the calculations -- place the appropriate Java statements after each comment.

3. So far the program does not print out the answer. Recall that the answer is the sequence of remainders written in reverse order -- note that this requires concatenating the four digits that have been computed. Since they are each integers, if we just use the + operator the computer will perform arithmetic instead of concatenation. But remember that if either operand to + is a string it will do concatenation, and that in the case of multiple + operations they are performed from left to right. So if you start by concatenating "" (the empty string), it will force the rest of the values to convert to strings -- essentially you are concatenating the values of the four place variables to the empty string. You can store the result in a String variable or just print it directly.

4. Compile and run your program. Test it using the following values: Enter 2 for the base and 13 for the base 10 number -- the program should print 1101 as the base 2 value; enter 8 for the base and 1878 for the number -- the program should print 3526 for the base 8 value; enter 3 for the base and 50 for the number -- the program should print 1212.

5. Print your program to hand in.

### Writing Classes: The Account Class

Program Account.java contains the Account class from the pre-lab.

1. Fill in your definitions for methods printSummary, chargeFee (returning the new balance) and changeName. Compile your class.

2. Program ManageAccounts.java contains the shell 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). Compile and run your program.

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

4. 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 printSummary method add a statement to print the number of transactions.
5. Classes often have accessor methods for each data value (see page 165 of the text). The getBalance method is an example of an accessor method. 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.
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).

5. Add an accessor method getName() to the Account class to return the name on the account.

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

7. Print Account.java and ManageAccounts.java.

### Writing Classes: Graphical Objects

In this exercise you will complete an applet that contains three snowmen holding balloons. Both the snowmen and the balloons will be graphical objects defined in separate classes.
1. The file Snowman.java contains the class that defines a graphical snowman (the same as the one on pages 103-104 except the code for the snowman has been encapsulated in a class). The file DrawSnowman.java contains a program that draws a sun and some steps. It instantiates a Snowman object and invokes the draw method of the Snowman class to draw the snowman. Save these files to your directory, compile the DrawSnowman.java program (which will also compile Snowman.java) then use the HTML file DrawSM.html and the appletviewer to view the applet.

2. Modify DrawSnowman.java as follows. Instantiate and draw two additional snowmen, one positioned on the step to the left of the current snowman and one to the right. Compile the program and view it. Make sure the snowmen are in the correct positions.

3. Listing 4.9 on pages 182 - 184 is the definition of a Circle class. The program on page 181 instantiates 5 Circle objects and draws them (note - they are drawn on a Panel rather than an Applet but the basic idea is the same as what we have been doing). The file Balloon.java contains a class similar to the Circle class (the accessor and mutator methods are not included). The file DrawBalloons.java instantiates and draws three objects of type Balloon. The file DrawB.html is an HTML file you can use for viewing the DrawBalloons applet. Save these files to your directory, compile, and run using the appletviewer. 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).

4. Modify Balloon.java so what is drawn looks like a balloon! To do this add a string (a straight line) hanging down from the balloon. The string should be twice as long as the balloon is high. Recompile DrawBalloons.java and see how the balloons look.

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

6. Print out Balloons.java and DrawSnowman.java to hand in.

### Hand In

• The six programs (Age.java, BaseConvert.java, Accounts.java, ManageAccounts.java, Balloons.java, and DrawSnowman.java).
• Tar your directory and email it to your instructor at roanoke.edu with the subject cpsc120 lab5.