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:
  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 9 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 names are 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-\).

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.

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

  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. The range will be given in feet. 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.

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.

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:

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

  1. Experiment with the coordinate system:
    1. First compile SimpleShape.java and then run the program. You should see a new window open displaying a blue oval.
    2. 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.
    3. 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?
    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.

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

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

To submit your code: Tar the files in your lab3 directory. To verify that the tar file contains the proper files, the partner that is not logged in should log in, cp the tgz file to their lab4 directory, untar the file, and do an ls to verify all of the files are there. Finally, to submit your code cp the tgz file to the directory:

   /home/staff/bouchard/CPSC120B/lab3