Lab 3 In-Class: Using Objects and Methods
Getting Started
Log onto the Linux system, open emacs, Mozilla, and an xterm window.
In Mozilla, 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
The following program illustrates the use of some of the methods in
the String class. Study the program to see what it is doing.
// ***************************************************************
// FILE: StringManips.java
//
// Purpose: Test several methods for manipulating String objects
// ***************************************************************
import java.util.Scanner;
public class StringManips
{
public static void main (String[] args)
{
String phrase = new String ("This is a String test.");
int phraseLength; // number of characters in the phrase String
int middleIndex; // index of the middle character in the String
String firstHalf; // first half of the phrase String
String secondHalf; // second half of the phrase String
String switchedPhrase; // a new phrase with original halves switched
Scanner scan = new Scanner (System.in);
// compute the length and middle index of the phrase
phraseLength = phrase.length();
middleIndex = phraseLength / 2;
// get the substring for each half of the phrase
firstHalf = phrase.substring(0,middleIndex);
secondHalf = phrase.substring(middleIndex, phraseLength);
// concatenate the firstHalf at the end of the secondHalf
switchedPhrase = secondHalf.concat(firstHalf);
// print information about the phrase
System.out.println();
System.out.println ("Original phrase: " + phrase);
System.out.println ("Length of the phrase: " + phraseLength +
" characters");
System.out.println ("Index of the middle: " + middleIndex);
System.out.println ("Character at the middle index: " +
phrase.charAt(middleIndex));
System.out.println ("Switched phrase: " + switchedPhrase);
System.out.println();
}
}
The file
StringManips.java contains this program.
Save the file to your lab3 directory (from Mozilla), compile and run it.
Study the output and make sure you understand the relationship between
the code and what is printed. Now open the file in emacs and make
the following modifications.
- Declare a variable of type String named middle3 (put your
declaration with the other declarations near the top of the program)
and use an assignment statement and the substring method
to assign middle3 the substring consisting of the middle
three characters of phrase (the character at the middle index
together with the character to the left of that and the one to the
right.) Write your assignment so it would work for any string, not
just the one instantiated in this example. To do that use
the middleIndex variable rather than integer literals
in your arguments for the substring method. Be sure to think about
where the statement should be placed in the program. Add a println statement
to print out the result, appropriately labeled.
Save, compile, and run to test what you have done so far.
- Add an assignment statement to replace all blank characters in
switchedPhrase with an asterisk (*). The result should be
stored back in switchedPhrase (so switchedPhrase is actually
changed). (Do not add another print -- place your statement in the
program so that this new value of switchedPhrase will be
the one printed in the current println statement.) Save, compile, and
run your program.
- Currently the program works for just the one phrase that is
instantiated when the phrase object is declared. Change the
program to get the phrase as input from the user as follows:
- Change the line that declares and instantiates phrase to
just a declaration.
- Add a prompt asking the user to enter a phrase and then add
a line to read the phrase in. The Scanner method to read in a string
is nextLine() which reads in everything entered on one line.
Be sure to correctly place these statements in the program.
Compile and run the program. Test it on strings of different lengths
and make sure it is printing the correct middle 3 characters.
- Declare two new variables city and state of type
String. Add statements to the program to prompt the user to enter
their hometown -- the city and the state. Read in the results using
the nextLine method. (NOTE: The city and state must
be entered on different lines to read them into separate
variables.) Then, using String class methods,
create and print a new string that consists of the state name (all in
uppercase letters) followed by the city name (all in lowercase letters)
followed again by the state name (uppercase). So, if the user enters
Lilesville for the city and North Carolina for the state, the program
should create and print the string
NORTH CAROLINAlilesvilleNORTH CAROLINA
- Print the final version of the program. Remember you can use the
print command you created last lab: ~/print StringManips.java
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
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
Write a complete Java program that simulates the rolling of a pair
of dice. For each die in the pair, the program should generate a
random number between 1 and 6 (inclusive). It should print out the
result of the roll for each die and the total roll (the sum of the
two dice), all appropriately labeled. You must use the Random class.
The LuckyNumber.java example from the Pre-Lab (which you can look at
by bringing it up in Mozilla) or the example on page 126 of the text
will help. Print your completed program.
Applets and Graphics
The following is a simple applet that draws a blue rectangle on a
yellow background.
// ****************************************************************
// FILE: RandomShapes.java
// Author:
//
// Purpose: The program will draw two filled rectangles and a
// filled oval positioned randomly on the screen.
// ****************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class RandomShapes extends JApplet
{
public void paint (Graphics page)
{
// Declare size constants
final int MAX_SIZE = 300;
final int PAGE_WIDTH = 600;
final int PAGE_HEIGHT = 400;
// Declare variables
int x, y; // x and y coordinates of upper left-corner of each shape
int width, height; // width and height of each shape
// Set the background color
setBackground (Color.yellow);
// 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 = 150;
width = 100;
height = 70;
// Draw the rectangle
page.fillRect(x, y, width, height);
}
}
Study the code noting the following:
Save the files
RandomShapes.java and
RandomShapes.html to your
lab3 directory. (Warning: When you click on the link to RandomShapes.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 RandomShapes.java. Normally an applet can be run
through a browser such as Mozilla
or IE. However, neither browser seems to run Java 1.5 applets (remember
the browser needs a bytecode interpreter in order to run Java bytecode -
it seems that the browsers have not been updated to the latest version
of Java). However, there is a special program, called the appletviewer,
that will run an applet. Run the program through the appletviewer
by typing the command
appletviewer RandomShapes.html
at the shell prompt in your xterm window. You should
see a new window open displaying a blue
rectangle on a yellow background (you may need to click on Applet, then
restart to get the background to show up).
- Close the applet window by clicking on Applet, then either close or
quit. The control character CTRL-C will also close the applet window.
- 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 rectangle?
- Now change the width to 200 and the height to 300. Save, recompile
and run to see how this affects the rectangle.
- 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 rectangle is random.
To do this you need to:
- 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 contant identifiers).
(Your random values should go up to but not include these maximums.)
- Modify the assignment statements to assign width and height
random values between 50 and MAX_SIZE + 50 (up to but not including
this value).
Save, recompile, and run the program to test the changes.
- Now add two more random rectangles -- this only requires duplicating
the code you already have so copying and pasting come in
handy. Highlight the code beginning with the "Set the color for the
next shape..." comment
through the command to draw the rectangle. You may copy this
using keystrokes (ESC-w copies, then CTRL-y pastes so you would
do ESC-w once and CTRL-y two times to get the three rectangles).
Test the changes.
- Change the colors for
at least two of the shapes so the
three shapes are different colors (a list of
colors is on page 95) AND change one of the fillRect methods
to fillOval so the final program draws two randomly positioned
and sized rectangles and one oval.
- Test your program in the Applet Viewer. Each time you restart the
appletviewer (either through Applet, restart from the menu or
re-executing the appletviewer command) the
program executes again, computing new random values for the positions
and sizes of the shapes.
- 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 centered
from left to right. Make the rectangle at least 100 pixels wide and 50
high.
- Use the drawString method (see the example on page 97 and
the description on page 100) to draw your name 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
correctly.
- Using Color objects You will now create your own colors
for the rectangle and string you just added.
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
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) will set the foreground
color for the page to be the color defined by the myColor object.
Do the following:
- Before the statement that draws the bottom rectangle add two statements:
Color myColor = new Color (200, 100, 255);
page.setColor(myColor);
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.
- Try a few other combinations of color codes to see what you get. Page
95 of the text shows you the codes for the pre-defined colors in the Color
class.
- Choose a color you like (not one of the pre-defined colors)
to be the rectangle color.
- Now 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.
HAND IN:
- Printouts of each of the four programs.
-
We're going to be trying out something new this lab. Instead of emailing your files to your instructor,
you will be submitting them using a script.
- First, make sure your lab3 directory is ready to submit. This means removing all .java~ files and any other
unnecessary files.
- From your lab3 directory, type cd ..
This should put you in the directory above your lab directory. So, if you type ls
you should see your lab3 directory listed.
- Now type submit120 lab3. Assuming you named your directory lab3, and not Lab3 or LAB3 or labs or lbas3.
You should see a message saying Copying directory lab3...Done. If you do not see this message, please
notify your lab assistant or instructor immediately.
- And that's it.