Lab 3 In-Class: Using Objects and Methods

Getting Started

Log onto Riddler, open emacs, Netscape, and an xterm window. In Netscape, 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
// Author:
//
// Purpose: Test several methods for manipulating String objects
// ***************************************************************

import cs1.Keyboard;

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

	// 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 Netscape), 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.
  1. 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). Add a println statement to print out the result. Save, compile, and run to test what you have done so far.
  2. 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.
  3. 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 appropriate Keyboard class method. 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
    
  4. 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

The file Distance.java contains an incomplete program 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 to print it out (appropriately labeled). 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.... 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 Netscape) or the example on page 97 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 java.applet.Applet;
import java.awt.*;

public class RandomShapes extends Applet
{
    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. Now do the following:

  1. Compile RandomShapes.java (but don't run -- this is an applet so it is run through a browser or a special program called the Applet Viewer).
  2. Run the program through the Netscape browser by choosing File, Open Page from the menu bar. Click on Choose File, then type in the complete path of the RandomShapes.html file (which should be ~/cpsc120/labs/lab3/RandomShapes.html), then click on Open in Navigator. You should see a blue rectangle on a yellow background.
  3. Now run the program through the Applet Viewer by typing the command
            appletviewer RandomShapes.html
    
    at the shell prompt in your xterm window. You should see a new window open displaying the rectangle.
  4. 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 (this is generally less trouble when making lots of changes than using the browser). What happened to the rectangle?
  5. Now change the width to 200 and the height to 300. Save, recompile and run to see how this affects the rectangle.
  6. Change x to 400, y to 40, width to 50 and height to 200. Test the program to see the effect.
  7. Modify the program so the position and size of the rectangle is random. To do this you need to
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 cutting (or 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 cut this using keystrokes (CTRL-w cuts, then CTRL-y pastes so you would do CTRL-w once and CTRL-y three times to get the three rectangles) or the Edit menu. Test the changes.
  • One last touch to the program ... Change the colors for at least two of the shapes so the background and each of the three shapes are different colors (a list of colors is on page 114) AND change one of the fillRect methods to fillOval so the final program draws two randomly positioned and sized rectangles and one oval.
  • After testing your program in the Applet Viewer, bring it up again in Netscape (first try opening the RandomShapes.html file again -- if you get the original version you may need to exit Netscape and re-start it). Now keep pressing the Reload button. Each time you do the program executes again, computing new random values for the positions and sizes of the shapes.
  • Print the final version of your program. HAND IN: