









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










In this exercise you will:
You have learned that a class is a template for an object in that it describes the object's characteristics and behaviors. Objects are built using the information in these templates. Thus, we say an object is an instance of a class. In this session, we are going to create and use objects defined by three of the classes in the Java API. They are JOptionPane, Random, and String.
When using an object defined in the API we are essentially using a black box. For example, without knowing about or understanding the inner workings of a television, we do know how to turn it on or off, how to change the channel, and how to increase or decrease the volume. That is, a television is essentially a black box that provides us with a way to use it. Similarly, when we create an object defined in the Java API, we do not need to know how it works. We only need to know how to use it by invoking one of its methods. The header of a method tells us how to properly invoke the method.
To use an object, we need to know what public methods are found in its defining class. The header of a method tells us how to use the method. The form of a method header is
optionalAccessModifiers returnType methodName ( optionalParameterList )
For example, the Scanner class has a method nextLine, whose header is
public String nextLine()
The methodName is nextLine. The returnType is String, meaning that this method returns a String that the program can then store or manipulate. This method has no parameterList , meaning that it does not need any additional information. The term public is an accessModifier that tells us that this method is available for the public to use. Thus, to use this method on an object named scan of type Scanner we write
line = scan.nextLine();
which assigns the returned String to the String variable line.
Another method is the parseInt method from the Integer class. The header for the method is
public static int parseInt(String s)
The method header tells us that the method parseInt has one formal parameter , s, of type String. Therefore, when the method is invoked it must be passed a String by placing either a String variable or String literal between the parentheses. The String that is passed is assigned to the formal parameter s. Inside the black box method, processing that uses s takes place, and when done, the method returns an int value to the user. Furthermore, the access modifier public tells us that this is one of the available methods, and the access modifier static tells us
myGUI.showMessageDialog(null,"I love Java!!");
Variables that are passed to a method are called the actual parameters; values that are passed to a method are called arguments. The first argument, null, is assigned to the formal parameter Component c. Simply put, null indicates that this JOptionPane is not attached to another Component or window. The second argument, "I love Java!!", is assigned to the formal parameter String s.
Step 1. Compile and execute J05E01.java. Record the results.
import javax.swing.*; class J05E { public static void main(String[] args) { JOptionPane myGUI = new JOptionPane(); } }
Step 2. Modify the program in Step 1 by adding this line of code to the main method.
myGUI.showMessageDialog(null, "I love Java!!");
Compile and execute the modified program. Describe what appears. Record what happens when the button is clicked.
Step 3. Modify the string to be printed, changing it to "I\nlove\nJava!!!". Compile and execute the program. Record the results.
Step 4. Remove the statement import.javax.*; from the program. How does the compiler inform you of this error?
The JOptionPane class also defines a method that allows the user to input information. The method header
public String showInputDialog(String prompt)
tells us that, when called, the method must be passed a String. The returned String can be saved, for future use, by assigning it to a String variable.
Step 1. Compile and execute the program J05E02.java. Describe what appears.
import javax.swing.*; class J05E { public static void main(String[] args) { JOptionPane myGUI = new JOptionPane(); String answer, greeting; answer = myGUI.showInputDialog("Enter your name"); greeting = "Hi " + answer; myGUI.showMessageDialog(null, greeting); } }
Random numbers are used in computer games and in simulations. For example, if five dice are rolled in a game of Yahtzee, the upturned face of each die must be a randomly chosen number between 1 and 6. Computer simulations are often used to predict behaviors in a complex system such as airport traffic. Random numbers can be used to generate arrival, departure, and waiting times to test the air traffic patterns. The computer simulation can provide valuable information to justify changes to the design of the airport.
The Java API defines a class Random in the java.util package. The Random class defines methods that return random int values and others that return random double values. The random numbers that are generated are actually calculated using sophisticated formulas that make them appear to be random. Therefore, these numbers are called pseudo-random numbers.
To declare and create a Random object, use the constructor Random().
Random rand = new Random();
To generate a random integer value, use the method
public int nextInt()
which has no formal parameters and returns a pseudo-random int value that lies between Integer.MIN_VALUE and Integer.MAX_VALUE. These statements correctly use the method.
int num; num = rand.nextInt();
To generate a random real value, use the method
public double nextDouble()
which has no formal parameters and returns a pseudo-random double value that lies between 0 and 1, including 0 but not including 1. These statements correctly use the method.
double realNum; realNum = rand.nextDouble();
Step 1. Compile and execute the program J05E03.java.
import java.util.*;
class J05E { public static void main(String[] args) { Random rand = new Random(); int num; for(int j = 0; j < 20; j++) { num = rand.nextInt(); System.out.println(num); } } }
Record the results by listing samples of the values that are generated.
Step 2. Modify the program to generate double values by adding the line
double realNum;
and replacing the line
num = rand.nextInt();
with
realNum = rand.nextDouble();
Compile and execute the program. List samples of values that are generated.
Usually the pseudo-random values that are generated must be modified to make them usable.
num = rand.nextInt(3) + 1;
Compile and execute the program. Record the results. What is the range of values obtained?
Step 4. To simulate the toss of a die, 6 numbers with values 1 through 6 are needed. Modify the existing program to simulate a die toss. Compile and execute the program. List your modifications and record the results. What is the range of values obtained?
We have been using String objects in every program that we have written. The String class is in the java.lang package, which is imported automatically into every program. To declare and create a String object we can follow the pattern established when we created the JOptionPane and Random objects.
String mouse = new String("Mickey Mouse");
The String class defines many interesting methods that we can use with String objects. First, let's look at these two methods:
public String toUpperCase()
and
public String toLowerCase()
To use either of these methods, invoke the method on a String object. No arguments are needed and a String object is returned. Can you predict what String is returned by each of these methods? Let's check it out.
Step 1. Compile and execute J05E05.java. Record the results.
class J05E { public static void main(String[] args) { String mouse = new String("Mickey Mouse"); System.out.println(mouse); System.out.println(mouse.toLowerCase()); } }
Step 2. Modify the code by replacing the statement toLowerCase() with toUpperCase(). Compile and execute the modified program. Record the results.
Step 3. Notice that we actually invoked the String method inside the println() method which prints the String that is returned by toLowerCase and toUpperCase. Let's change this. Modify the code by replacing the statement
System.out.println(mouse.toUpperCase());
with the two statements
mouse.toUpperCase(); System.out.println(mouse);
Compile and execute the modified program. Record the results.
Compile and execute the program. Record the result.
Every String object has a length representing the number of characters in the string. If
String river = "Nile";
then the length of river is 4. The String class defines the method
public int length()
that returns the length of this String. This code assigns 4 to int len:
len = river.length();
Each of the characters stored in a String object has an associated number called an index. The index of the first character in the string is always 0. The indices of the second, third and fourth characters are 1, 2 and 3, respectively. Note that a string with length 4 has characters with indices 0,1,2 and 3.
The String class also defines the method
public char charAt(int index)
that returns the character at index. This code assigns 'N' to char c;
c = river.charAt(0);
Step 1. Compile and execute the program J05E06.java. Record the results.
class J05E { public static void main(String[] args) { String river = "Amazon";
int len = river.length(); System.out.println(river + " has length " + len);
Char c = river.charAt(0); System.out.println(c); } }
Step 2. Modify the code by passing 3 to the charAt method instead of 0. Predict the results, then compile and execute the program. Record the results.
Step 3. Modify the existing code by replacing the statement
c = river.charAt(3);
with the statement
c = river.charAt(len);
Predict the results, then compile and execute the program. Record the results.
Step 4. Modify the code by replacing the last three statements with a for loop that prints every letter of river on a separate line. I'll start you off, but you should finish the code by filling in the first line of the for loop. The condition of the loop should use the variable len.
for(int j = ) { c = river.charAt(j); System.out.println(c); }
10 0
Step 2. Modify the program by replacing the 1 in river.substring(1) with each of the integers listed in the above table. Record the results in the table above.
Step 3. What is returned by the method substring(int index)?
Step 4. The method substring is an overloaded method. The second method has header
public String substring(int beginIndex, int endIndex)
Replace the statement
myGUI.showMessageDialog(null, river.substring(1));
with the statement
myGUI.showMessageDialog(null, river.substring(1,5));
Compile and execute the program. Record the results in the first line of the following table.
beginIndex endIndex (^) river.substring(beginIndex, endIndex) returns 1 5 1 7 4 4 4 7 5 9 0 4
Step 5. Modify the program by replacing the 1 and 5 in river.substring(1,5) with each of the integers listed in the above table. Record the results in the table.
Step 6. What is returned by the method substring(int beginIndex, int endIndex)?