Lab 3 In-Class: Using Objects and Methods
Lab Objectives
- Gain experience using objects and methods in the String
class and the Random class (from the Java standard class library).
- Gain experience using static methods in the Math class.
- Write a simple application using basic graphics.
|
Getting Started
Log onto the Linux system, open Firefox, Emacs, and an xterm window.
In Firefox, go to the home page for this class and open up this lab.
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 80 of the text
(in fact it uses a string from that example) and those from class and pre-lab.
Save the program to your lab3 directory, and open it in emacs using
either CTRL-x CTRL-f or "Visit New File" from the menu.
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 9 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).
- Be sure your name is in the header documentation of the program
and that the program is correctly formatted (select the program
either using the mouse or CTRL-x CTRL-p, then press CTRL-ALT-\)
then print the program (remember the print command from lab 2).
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. In particular, the substring
method requires you to specify the starting index of the substring
you want to extract and the index of the character that marks the
end of the substring (the index of the character that is one character
beyond the last character in the substring).
For example in the declaration above we would need the indices
of the positions indicated in the following diagrams
to extract the variable type, the variable
name, and the initial value from the declaration/initialization
statement:
double price = 34.56;
^ ^
^ ^
| |
Variable type: starts goes up to
here (but does not
include) here
double price = 34.56;
^ ^
^ ^
| |
Variable name: starts goes up to
here (but does not
include) here
double price = 34.56;
^ ^
^ ^
| |
Initial value: starts goes up to
here (but does not
include) here
Of course for this particular example we could count to find the
indices. However we want a more general approach that would
work for every declaration/initialization statement that is
in the correct form.
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.
Notice in the example above, the first blank space marks the end
of the type (the word "double" in this case).
So, 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
type, right?).
Similarly knowing the index of the first blank space also lets us know the
index of the first character in the variable name (we assume there is
only one blank space) - what is the relationship between the
index of the first blank
character and the index of the first character in the variable name?
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.
The program should work correctly for declaration/initialization statements
that have correct syntax including the semi-colon at the end.
Print your program to hand in.
Using the Math Class - Exercise #3
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 (in standard format for 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. The range will
be given in feet.
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 methods from the Math library.
- Finally, add a statement to print out the answer, appropriately
labeled.
- 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 - Exercise #4
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.
Print the completed program.
Graphics - Exercise #5
The following is a simple application that draws a filled blue oval:
import javax.swing.JFrame;
import java.awt.*;
// ***************************************************************
// Draws simple shapes on the screen in random positions.
//
// Author - YOU
// ***************************************************************
public class SimpleShape extends JFrame
{
//******************************************
//Create and display application frame
//******************************************
public static void main(String[] args)
{
SimpleShapeApp frame = new SimpleShapeApp();
frame.setSize(600, 400);
frame.setVisible(true);
}
//***************************************************************
//Assign random position and size then draw each of 3 shapes.
//***************************************************************
public void paint(Graphics page)
{
// Declare size constants
final int PAGE_WIDTH = getWidth();
final int PAGE_HEIGHT = getHeight();
// Draw a rectangle in the background color to cover the whole window
page.setColor(Color.white);
page.fillRect(0, 0, PAGE_WIDTH, PAGE_HEIGHT);
// 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
page.setColor(Color.blue);
// Assign the corner point and width and height
x = 200;
y = 125;
width = 200;
height = 150;
// Draw the oval
page.fillOval(x, y, width, height);
}
}
Study the code noting the following:
- The program imports javax.swing.JFrame because it creates a window
and it imports java.awt.* because it uses graphics. In java a JFrame is a
type of window that defines methods useful in setting a window's contents.
- The "extends JFrame" part of the class header makes the SimpleShape class
a subclass of JFrame, so it inherits many of its methods. This includes the
paint method that is defined after the main method. The paint method is
automatically invoked every time the window needs to be redrawn (this includes
if the window is resized, or if it is hidden by another window and then revealed).
- Most of the methods that draw shapes (see the list on page 806),
including the fillOval method used in this example,
require parameters that specify the upper left-hand corner of the
shape (using the coordinate system described on page 804) and
the width and the height of the shape.
- The main method specifies the initial height and width of the window to be 600
pixels wide and 400 pixels high. The size of the window can be changed by a user by dragging
a corner of the window, so the first two statements in the paint function put the
current width and height of the window into two constants, PAGE_WIDTH and PAGE_HEIGHT.
The size of the window can not change while the paint method is being executed, so these values will be constant through the execution of the method.
Save the file
SimpleShape.java to your
lab3 directory. Now do the following:
- Experiment with the coordinate system:
- First compile SimpleShape.java and then run the program.
You should
see a new window open displaying a blue oval.
- Close the application window by clicking clicking the corner X. You
may need to press CTRL-C in the terminal window to get your prompt
back.
- Open SimpleShape.java in Emacs and change the x and y variables both to 0.
Save, compile, and run the appication again. What happened to the oval?
- Now change the width to 150 and the height to 300.
Run to see how this affects the oval.
- Change x to 400, y to 40, width to 50 and height to 200. Test
the program to see the effect.
- Modify the program so the position and size of the oval is
random. To do this you need to do the following:
- Add the command to import the java.util.Random class.
- Declare and instantiate a Random object named generator.
- Modify the assignment statements to assign x a random value between
0 and PAGE_WIDTH and y a random value between 0 and PAGE_HEIGHT (use these
constant identifiers). (Your random values should go from 0 up to but
not including PAGE_WIDTH and PAGE_HEIGHT.)
- Modify the assignment statements to assign width and height random
values from 50 up to but not including 250.
Run the program to test the changes.
- Now add two more random ovals. This only requires duplicating the code
you already have for one oval (setting the color, computing random
position and size info, and drawing the shape) - just copy and paste.
- One last touch to the program --- Change the colors for at least two
of the shapes so the three shapes are different colors (a list of colors is
on page 805) AND change one of the fillOval methods to fillRect
so the final program draws two ovals and one rectangle. Be sure to
run the application to test your changes.
- Print the final version of your program.
HAND IN:
- Printouts of each of the five programs.
- Be sure you are in your lab3 directory then
tar the files in the directory with the following command
(remember the dot - you are tarring your current
directory):
tar czf lab3.tgz .
- Email the .tgz file
to your instructor (ingram or bouchard) at roanoke.edu with a
subject of cpsc120 lab3.