Lab 3 In-Class: Using Objects and Methods
Log onto the Linux system, open emacs, Firefox, and an xterm window.
In Firefox, go to the home page for this class and open up this lab.
In an xterm,
go to your labs directory for this course and create a lab3
subdirectory for today's work. Change into that subdirectory.
Using the String Class - Exercise #1
The file StringManip.java contains a partially
completed program to manipulate strings. You will complete the program
by adding statements that invoke methods in the String class.
Your program will be similar to the example on page 120 of the text
(in fact it uses a string from that example) and those in pre-lab.
Save the program to your directory, open
it in emacs and do the following:
- Study the program to see what is already there.
- Follow the comments to add statements to complete the
program (the comments indicating things you are to do start with
*** - there are 8 of them).
- Compile and run the program. Test it on several ending
phrases (for example the ending phrase in your book's program is
except from vending machines).
Using the String Class - Exercise #2
One part of a compiler's job in translating a program is to parse the
program - that is, it must read the program and break it up into its
key parts (often called tokens). In this exercise you will complete a
program that takes as input a Java declaration/initialization
(which is a String) and breaks it up into its three main components:
the type, variable name, and value. For example, if the user types
in the following declaration/initialization:
double price = 34.56;
The program should produce output as follows:
Variable Type: double
Variable Name: price
Initial Value: 34.56
The program will use methods from the String class to determine the
parts of the string. Clearly the type, variable name, and the
initial value of the variable are all substrings of the original
statement so the substring method will be very important. However,
the substring method needs to have some information about where (the
indices) to break the string up. For that, the indexOf method is
very useful. The following is the signature for the method.
int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring (str).
For example, suppose we have the following:
String title = "Java Software Solutions";
Then, title.indexOf("Soft") would be 5, the index of the beginning
of the string "Soft" in the title. Similarly, title.indexOf("v") would
be 2, the index of the first occurrence of the letter v.
We can use the
indexOf method to find the locations of the
characters that separate the parts of the declaration/initialization.
For example, if we know the index of the first blank space we can extract
the substring for the type (that would tell us the index of the blank space
that marks the end of the type and we know the index of the beginning of the
Download the file DeclarationParse.java,
open it in emacs, and complete the program using the comments as a guide.
Be sure to test the program on several different declaration/initializations.
Using the Math Class
In this exercise you will complete a program that computes two
different distances. The first is the distance
between two points in an ordinary coordinate system; the
second is the horizontal distance that a projectile (such as a ball)
will go when launched (thrown) at a given angle with a given initial
velocity. The file Distance.java contains an
incomplete program. Complete it as follows.
- First add code to compute the distance between two points. Recall
that the distance between the two points (x1, y1) and (x2, y2) is
computed by taking the square root of the quantity (x1 - x2)2 +
(y1 - y2)2. The program already has code to get the
two points as input. You need to add an assignment statement to
compute the distance and then a print statement that prints out
the points and the distance.
Test your program using the following data: The distance between
the points (3, 17) and (8, 10) is 8.6023... (lots more digits printed);
the distance between (-33, 49) and (-9, -15) is 68.352....
- Now add the code to compute the second distance - the distance a
projectile will travel given the initial velocity and the angle. The
variables and constants are already declared. The formula for
the distance traveled (range) is
range = sin(2*angle) * velocity2 / g
where g is the gravitational constant (which is about 32.174 feet/sec/sec
in English units) and the angle is measured in radians.
You need to:
- Add code to prompt the user to enter the initial velocity (in feet/sec)
and the angle (in degrees) the projectile will be thrown, then
read in these values. (NOTE: Use the variables already declared.)
- Convert the number of degrees to radians. The formula is:
the number of radians equals the number of degrees times PI divided by 180.
Use the constant Math.PI from the Math library for the value of
PI (this is much more accurate than defining your own constant).
- Now compute the range using the above formula. Use both the
sin and the pow functions from the Math library.
- Finally, add a statement to print out the answer, appropriately
- Test your calculations: If the projectile is thrown with
an initial velocity of 55 feet/sec and an angle of 35 degrees, its
range would be about 88.3499... feet; if the initial velocity is 40 feet/sec
and the angle is 50 degrees, the range is about 48.97409... feet.
- Print the completed program.
Using the Random Class
Your friend is a DJ for the college radio station. To boost
the ratings for her show, she is sponsoring a
contest where the winner is the first student to call in with a birthday
matching the announced "WRKE Super Prize Birthday".
To be fair, she wants the "WRKE Super Prize Birthday" to be selected at random.
Write a complete Java program that will randomly generate a month (1-12) and
day (1-31) for her to announce on the air. Your program should print out a
message that includes some text (e.g. "The WRKE Super Prize Birthday is: ")
as well as the
numeric representation of the date (e.g. "2/28"). Your program must
include comments to explain why you will occasionally produce
an invalid date.
Applets and Graphics
The following is a simple applet that draws a circle on the screen
// FILE: SimpleShape.java
// Purpose: The program will draw a simple shape on the screen
public class SimpleShape extends JApplet
public void paint (Graphics page)
// Declare size constants
final int PAGE_WIDTH = 600;
final int PAGE_HEIGHT = 400;
// Declare variables
int x, y; // x and y coordinates of upper left-corner of the shape
int width, height; // width and height of the shape
// Set the color for the next shape to be drawn
// Assign the corner point and width and height
x = 200;
y = 100;
width = 200;
height = 200;
page.drawOval(x, y, width, height);
Study the code noting the following:
Save the files
SimpleShape.html to your
lab3 directory. (Warning: When you click on the link to SimpleShape.html
the applet will start running. Using the File, Save As ... option will
save the HTML code above.) Now do the following:
- Experiment with the coordinate system:
- Compile SimpleShape.java. Normally an applet can be run
through a browser such as Mozilla Firefox
or IE. However, occasionally a browser will not run Java 1.5 applets (remember
the browser needs a bytecode interpreter in order to run Java bytecode -
some browsers have not been updated to the latest version
of Java). For program development, there is a special program,
called the appletviewer,
that will run an applet. Run the program through the appletviewer
by typing the command
at the shell prompt in your xterm window. You should
see a new window open displaying a blue circle.
- Close the applet window by clicking on Applet, then either close or
quit, or just clicking the X.
- Now open the program in emacs and change the x and y variables both to 0.
Save and recompile the program, then view it in the Applet
Viewer. What happened to the circle?
- Now change the width to 200 and the height to 300. Save, recompile
and run to see how this affects the circle.
- Change x to 400, y to 40, width to 50 and height to 200. Test
the program to see the effect.
- Copy the program to a new file named Darts.java. We are going to
expand this applet to draw a dartboard and throw some darts.
To do this we will need
to follow several steps
- Open the Darts.java file and make the necessary changes to make it
- Remember that applets are embedded in HTML documents - so copy the
SimpleShape.html to Darts.html and make the necessary changes to that file.
- Use the drawOval method to draw 4 concentric circles that are located in
the center of the viewing window. Start with a big one:
- Once you have the dartboard drawn,lets add some darts.
To represent a dart, we are going to use the
drawLine method, which works as follows:
void drawLine (int x1, int y1, int x2, int y2)
// draws a line from the point (x1,y1) to the point (x2,y2)
Use two drawline methods to draw a dart shaped like an 'X' that is 9 pixels
wide by 9 pixels high, centered on the page.
- Now lets use the Random class to simulate throwing 3 darts at the board.
To do this, you will need to
- Add the command to import the java.util.Random class.
- Declare and instantiate a Random object named generator
- Declare two variables to hold the center coordinates of a dart.
- Use generator to get random values that can be assigned to the coordinates
of the dart (Be mindful of the boundaries for your random numbers) and then
draw the dart on the screen.
- Compile and view the applet to make sure all is well.
- Repeat the last step to handle multiple darts.
- Go back into your code and change all the drawOval commands to fillOval
commands. Save, recompile and execute. What happened to all your circles?
Since your circles overlap, you will need to change the color for each circle
to make them distinct. You can do this by using the setColor method.
void setColor(Color color)
Notice that this method takes a color object as a parameter. A list of
predefined colors objects can be found on page 93 of your textbook.
Adjust your code to use the setColor method to make each circle a
- Add a rectangle with your name in it at the bottom of the
applet window as follows:
- Draw a rectangle at the bottom of the applet window using the
fillRect method (see the example on page 100 and
the description on page 98).
Position the rectangle so that it is in the lower right corner of the screen.
Make the rectangle at least 100 pixels wide and 50
- Use the
drawString method to draw your name (approximately)
centered in the
rectangle you just added. Note that for your name to show up, it must
be in a different color than the rectangle. So, after drawing the
rectangle, set the color to something different, then draw the string.
- Test your program - be sure the rectangle and string are placed
- Using Color objects You will now learn how to create your own
colors for the shapes that you have been drawing.
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 2.7 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 rather then using
the pre-defined colors, such as Color.red,
from the Color class. 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
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) will set the foreground
color for the page to be the color defined by the myColor object.
Do the following:
- Immediately before the statement that draws the rectangle
add two statements:
Color myColor = new Color (200, 100, 255);
The first 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. The second sets the foreground color to be
that color (so anything drawn afterwards will be that color). Compile and
run the applet using the appletviewer.
- Change the instantiation (constructor) so the color code is
(0,0,0) --- absence of
color. What color should this be? Run the program to check.
- Choose a set of colors you like (not the pre-defined colors)
to use for the rectangle.
- Replace the statement that sets the color of your name with
two statements - one that creates a new color for the string (use
a color object) and the other that sets the foreground color to the
color you created. Make sure the color you choose shows up so your
name is visible!
Print the final version of your program.
- Printouts of each of the five programs.
- Tar the files in your lab3 directory with the command
tar czf lab3.tgz .
and email the .tgz file
to your instructor (ingram or hughes) at roanoke.edu with a
subject of cpsc120 lab3.