Lab 5 In-Class: Exploring Data Representation &
Conditional (if) Statements
Log onto the Linux system and create a lab5 subdirectory of your cpsc120/labs
directory for today's work. As usual, you will need to have three windows open:
an xterm, emacs, and Netscape.
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:
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).
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 Netscape,
save it to your lab5 subdirectory, then open it in emacs. Modify
the program one step at a time as follows:
- 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.
- Now it is time to add the code to do the conversion.
The comments below guide you through the calculations --
replace them with the appropriate Java statements.
// First compute place0 -- the units place. Remember this comes
// from the first division so it is the remainder when the
// base 10 number is divided by the base (HINT %).
// Then compute the quotient (integer division / will do it!) -
// declare a new variable for the quotient
// Now compute place1 -- this is the remainder when the quotient
// from the preceding step is divided by the base.
// Then compute the new quotient
// Repeat the idea from above to compute place2 and the next quotient
// Repeat again to compute place3
- 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 add them the computer will perform arithmetic
instead of concatenation. So, we will use a variable of type String.
Near the top of the program a variable named baseBNum has been declared
as an object of type String and initialized to an empty string. Add statements
to the program to concatenate the digits (using the + operator)
in the new base to baseBNum
and then print the answer. 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.
- Don't print your program yet! You are going to add something to it later.
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. For example, the following
declares the Color object myColor and instantiates it to a color
with code 255 for red, 0 for green, and 255 for blue.
Color myColor = new Color(255, 0, 255);
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
defines myColor to be a Color object with color code (200, 100, 255) -
a shade of purple. Save the program and its associated HTML file
Colors.html to your lab5 directory, compile and
run it using the appletviewer. Now make the following modifications:
- Change the constructor so the color code is (0,0,0) --- absence of
color. What color should this be? Run the program to check.
- 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
- 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
should represent pure green. Its base 10 value is 65280. Change the
declaration of the myColor object to
Color myColor = new Color (65280);
Compile and run the program. Do you see green?
- 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.
- declare generator to be an object of type Random (the import statement
is already there);
- declare colorCode to be a variable of type int;
- assign colorCode a random integer value (use the nextInt()
- replace the number 65280 in the Color constructor above with the
- The Color class has methods that return the individual color codes (for
red, green, and blue) for a Color object. For example,
redCode = myColor.getRed();
returns the code for the red component of the myColor object (redCode
should be a variable of type int). The methods
that return the green and blue components are getGreen and
getBlue, respectively. Add statements to the program, similar
to the above, to get the three color codes (you need to declare some
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.
- Don't print yet -- you will be adding a statement later.
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)
In this example the condition is toss == 0, where == is
the "equal" operator. (Remember a single = mark is the assignment
if (numStudents > 0)
testAverage = sumOfGrades / numStudents;
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:
- Save the file to your directory and open it in emacs.
- 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
- 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).
- Suppose the charge for sewer services is also based on water usage. A person
who uses less than 7500 gallons of water pays a flat rate of $7.50 for sewer but
a person who uses more pays $0.001 per gallon. Add an if ... else... to the
program to compute the sewer charge. Update other parts of the program to
take this into account -- update the calculation of the total bill and add
a statement to print the sewer charge in the bill.
- 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:
- 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.
- Write an if to compute the utility tax.
- Add the utility tax to the total bill.
- Print the utility tax as part of the bill.
- 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)!
- 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.
Add an if to the Color Code Program
Retrieve the emacs buffer containing the Colors.java program. Add
if ... else ... statements to determine which is the dominant hue --
red, green, or blue -- in the myColor object.
You need to determine which of the variables
redCode, greenCode, and blueCode is the largest.
You can do this with a nested if (if's within an if) as in the example
on page 143 OR you can use the boolean operator AND (&&).
Draw a string below the rectangle that prints a message indicating
the dominate hue (for example, if the color codes are 100 for red, 230
for green, and 40 for blue your message would say that Green is the
Print a copy of your program.
- The three programs
(BaseConvert.java, Colors.java, and WaterBill.java).
- Tar your directory and email it to your instructor at roanoke.edu with the
subject cpsc120 lab5.