Lab 3 In-Class: Using Objects and Methods

Lab Objectives

  • Mount your Z drive (your personal space on the RC Windows file server) in Linux.
  • 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 applet using basic graphics.

Getting Started

Log onto the Linux system, open 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.

Mounting Your Z Drive

If you do some of your assignments in Windows you must transfer your programs to Linux and print them (or you need the equivalent of the nenscript command on your Windows machine to get a nice two-column printout). You could send your programs to yourself through email and then use Firefox to download them to Linux OR you could save your program on the Windows network file server (the Z drive) and access that from Linux. Do the following to mount your Z drive in Linux: This will create an icon called myZ on your desktop. It should be there whenever you log on (you don't need to do the above steps again!).

Using your Z drive: Double click on the myZ icon. You will get a dialog box asking you to enter your password (this is your RC email password). You will then get a file browser window showing you the contents of your Z drive. From the file browser you can drag files and folders and drop them on your desktop. To drop files into your directory structure on Linux, open another file browser window by clicking on Places then Home Folder. You can drag and drop between directories in Linux and the Z drive on Windows.

Try this out. If you don't have anything saved on your Z drive, create a CS120 folder there (choose File, Create Folder from the menu bar in the myZ browser window), then drag a program from your lab2 subdirectory on Linux into the CS120 folder on windows.

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 from class and pre-lab. Save the program to your directory, launch Eclipse, and find the program in the left-most panel (you may need to press F5 to refresh to see it in your lab3 package). Do the following:
  1. Study the program to see what is already there.
  2. 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).
  3. 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).
  4. Be sure your name is in the header documentation of the program and that the program is correctly formatted (press SHIFT-CTRL-F or choose Source/Format from the menu) 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. 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 type, right?).

Download the file DeclarationParse.java, open it in Eclipse, 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

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

  2. 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:
    1. 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.)
    2. 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).
    3. Now compute the range using the above formula. Use both the sin and the pow methods from the Math library.
    4. Finally, add a statement to print out the answer, appropriately labeled.
    5. 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.
    6. 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.

Print the completed program.

Applets and Graphics

The following is a simple applet that draws a filled blue oval:
package lab3;

/**
 *
 * Draws simple shapes on the screen in random positions.
 *
 * @author J. Ingram
*/

import javax.swing.JApplet;
import java.awt.*;

public class SimpleShape extends JApplet
  {
    public void paint (Graphics page)
      {
	// Declare size constants 
	final int PAGE_WIDTH = 600;
	final int PAGE_HEIGHT = 400;
        resize (PAGE_WIDTH, PAGE_HEIGHT);

        // 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:

Save the file SimpleShape.java to your lab3 directory. Now do the following:

  1. Experiment with the coordinate system:
    1. Open SimpleShapes.java in Eclipse. Click on Run As, then Java Applet. You should see a new window open displaying a blue oval.
    2. Close the applet window by clicking on Applet, then either close or quit, or just clicking the corner X.
    3. Now change the x and y variables both to 0. Run the applet again. What happened to the oval?
    4. Now change the width to 150 and the height to 300. Run to see how this affects the oval.
    5. Change x to 400, y to 40, width to 50 and height to 200. Test the program to see the effect.

  2. Modify the program so the position and size of the oval is random. To do this you need to do the following:
    1. Add the command to import the java.util.Random class.
    2. Declare and instantiate a Random object named generator.
    3. 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.)
    4. 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. In the applet window choose Applet, then Restart to see the oval change positions.

  3. Now add two more random ovals. This only requires duplicating the code you already have - just copy and paste.

  4. 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 93) AND change one of the fillOval methods to fillRect so the final program draws two ovals and one rectangle. Be sure to run the applet to test your changes.

  • Print the final version of your program.

    HAND IN: