Lab 5 In-Class: Exploring Data Representation & Conditional (if) Statements

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?

Write 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. The program should have the following features: 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.

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,

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

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.

 

 

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. Don't print your program yet! You are going to add something to it later.

 

 

Color Codes

The basic scheme for representing a picture in a computer is to break the picture down into small elements called pixels and then represent the color of each pixel by a numeric code (this idea is discussed in section 1.5 of the text). In most computer languages, including Java, the color is specified by three numbers -- one representing the amount of red in the color, another the amount of green, and the third the amount of blue. These numbers are referred to as the RGB value of the color. In Java, each of the three primary colors is represented by an 8-bit code. Hence, the possible base 10 values for each have a range of 0-255. Zero means none of that color while 255 means the maximum amount of the color. Pure red is represented by 255 for red, 0 for green, and 0 for blue, while magenta is a mix of red and blue (255 for red, 0 for green, and 255 for blue). In Java you can create your own colors. So far in the graphics programs we have written we have used the pre-defined colors, such as Color.red, from the Color class. However, we may also create our own Color object and use it in a graphics program. One way to create a Color object is to declare a variable of type Color and instantiate it using the constructor that requires three integer parameters -- the first representing the amount of red, the second the amount of green, and the third the amount of blue in the color. The signature for the constructor is
           Color (int r, int g, int b)
where r is the integer code for red, g the code for green, and b the code for blue. In a program we could declare the Color object myColor and instantiate it to a color with code 255 for red, 0 for green, and 255 for blue. Then the statement page.setColor(myColor) then will set the foreground color for the page to be the color defined by the myColor object.

The file Colors.java contains an applet that you will use to experiment with your own colors (and random colors). Save the program and its associated HTML file Colors.html to your lab5 directory, then do the following:

  1. Add a statement (as directed by the comment in the program) that declares myColor to be a Color object and instantiates it to be the color with color code 200 for red, 100 for green, and 255 for blue - this gives a shade of purple. Compile and run the applet using the appletviewer.

  2. Change the constructor so the color code is (0,0,0) --- absence of color. What color should this be? Run the program to check.

  3. Try a few other combinations of color codes to see what you get. Page 793 of the text shows you the codes for the pre-defined colors in the Color class.

  4. Now we will modify the program to generate random colors. Notice on page 793 of the text that there is a constructor for the Color class that takes a single integer as an argument. The first 8 bits of this integer are ignored while the last 24 bits define the color -- 8 bits for red, 8 for green, and the last 8 bits for blue. Hence, the bit pattern
            00000000000000001111111100000000
    
    should represent pure green. Its base 10 value is 65280. Change the declaration of the myColor object to instantiate myColor to be an object with color represented by the single integer 65280. Compile and run the program. Do you see green?

  5. Now add the following statements to the program:

    Compile and run the program -- reload the program several times so you can see the different random colors generated.

  6. The Color class has methods that return the individual color codes (for red, green, and blue) for a Color object. For example, the getRed() method returns the code for the red component of the myColor object. The methods that return the green and blue components are getGreen() and getBlue(), respectively. Add statements to the program to declare three integer variables redCode, greenCode, and blueCode and to get the three color codes and assign them to the appropriate variables. Then add statements such as
            page.drawString("Red: " + redCode, ____ , ____ );
    
    to label the rectangle with the three color codes (fill in the blanks with appropriate coordinates so each string is drawn inside the rectangle -- you also need to set the drawing color to something such as black so the strings will show up). Compile and run the program to make sure it works. Reload several times to see the different colors and their corresponding codes displayed.

A Program Using If Statements (Conditionals)

A conditional statement (also called a selection statement) in a programming language is one that allows a choice as to which statement is executed next. That choice is based on some condition -- a boolean expression that is either true or false. In Java (and most other programming languages) two of the conditional statements are if and if ... else... . If and if ... else... statements are discussed in Section 3.2 of the text. An if statement is used when you want to do something when some condition is true but do nothing otherwise. Some examples are:
       if (grade >= 90)
         System.out.println ("Congrats!  You made an A!");
In this example the condition is grade >= 90 (grade would be a variable given a value earlier in the program). If it is true (if the value of the variable grade is greater than or equal to 90 when this statement is executed) the congratulation statement would be printed; otherwise it will not be printed.
       if (numStudents != 0)
          testAverage = sumOfGrades / numStudents;
In this example, the condition is numStudents != 0. != is the "not equal" operator. If the value of the variable numStudents is not equal to 0 when the condition is evaluated, the assignment statement will be evaluated.

An if ... else ... statement is used when you want to do one thing when a condition is true but something else when it is false. Some examples are

        toss = Math.abs (generator.nextInt()) % 2;
        if (toss == 0)
           System.out.println ("Tails");
        else
           System.out.println ("Heads");
In this example the condition is toss == 0, where == is the "equal" operator. (Remember a single = mark is the assignment operator.)
        if (numStudents > 0)
           testAverage = sumOfGrades / numStudents;
        else
           System.out.println ("You must have at least one student!!");

The file WaterBill.java contains a program to compute a customer's water and sewer bill. The charge for water is based on consumption -- a customer who uses no more than 7500 gallons in a month pays $0.002 per gallon but a customer who uses more pays $0.002 per gallon for the first 7500 gallons plus $0.0035 per gallon for each gallon over 7500. Note that the charge depends on a condition -- whether or not the amount of water used is over 7500 gallons. Hence an if is needed to compute the charge for the water. Do the following:

  1. Save the file to your directory and open it in emacs.

  2. Study the code and find the if... else... that computes the charge for the water -- there are two different formulas used for the calculation depending on whether numGals is less than or equal to CUTOFF (7500) or not. Also notice near the bottom of the program an if that prints a message for customers who use less than half of 7500.

  3. Run the program several times. Enter numbers greater than 7500 (such as 10000), numbers between 7500 and half of 7500 (such as 6000), and numbers less than half of 7500 (such as 3000).

  4. Add an if ... else... to the program to compute the sewer charge. Suppose the charge for sewer services is also based on water usage. A person who uses less than 7500 gallons of water pays $0.001 for sewer but a person who uses more pays $7.50 for the first 7500 gallons plus $0.003 per gallon for each gallon over 7500 (so, for example, a person who used 8500 gallons would pay $7.50 + $3.00 = $10.50).

  5. Update other parts of the program to take the sewer charge into account -- update the calculation of the total bill to include the sewer charge and add a statement to print the sewer charge in the bill.

  6. Suppose senior citizens get a break on the utility tax. The tax rate for senior citizens is 8.5% but it is 12% for all others. Add statements to the program to compute the tax. This requires that you find out if the customer is a senior citizen! Use a variable of type char for this. You need to do the following:
    1. Add a prompt that asks the user to answer the question "Are you a senior citizen?" by entering a y or n. Use the Keyboard class to read in the answer (as a char not a String); store the answer in the variable senior.
    2. Write an if to compute the utility tax (note: the tax is on the total bill).
    3. Add the utility tax to the total bill.
    4. Print the utility tax as part of the bill.

  7. Add an if statement that prints a warning to customers who use more than 3 times the cut off (7500) gallons. Warn them that they are subject to a $500 fine if their excessive water use continues (just print a message -- don't add the fine to their bill)!

  8. Be sure your program works correctly, then print it.

Adding an if to the Base Conversion Program

Get your base conversion program back (note -- instead of re-opening it, look under buffers on the emacs menu bar, then click on BaseConversion.java). Remember that this program only computes 4 digits in the new base so if the user enters a number that is too large to fit in 4 digits the answer produced by the program is incorrect (it is incomplete -- it only gives the rightmost 4 digits). Unfortunately a lot of people believe the computer so we need to be sure the computer doesn't print out incorrect information. Replace the statement that prints the answer with an if ... else ... If the number is too large to fit in 4 digits in the new base print a message saying so (remember you calculated the maximum number that will fit); otherwise, print the answer. To test the program, use the following input: 4 for the base and 375 for the base 10 number (the program should say 375 is too big to fit in a 4-digit base 4 number); 7 for the base and 5341 for the number (again, too big); 7 for the base and 537 for the base 10 number (the program should print 1365).

Print a copy of your program.

Hand In