Chapter10 Lab
Chapter10 Lab
Lab Exercises
Topics Lab Exercises
Exceptions Exceptions Aren’t Always Errors
Placing Exception Handlers
Throwing Exceptions
1. Run CountLetters and enter a phrase, that is, more than one word with spaces or other punctuation in between. It should
throw an ArrayIndexOutOfBoundsException, because a non-letter will generate an index that is not between 0 and 25. It
might be desirable to allow non-letter characters, but not count them. Of course, you could explicitly test the value of the
character to see if it is between 'A' and 'Z'. However, an alternative is to go ahead and use the translated character as an
index, and catch an ArrayIndexOutOfBoundsException if it occurs. Since you want don't want to do anything when a
non-letter occurs, the handler will be empty. Modify this method to do this as follows:
Put the body of the first for loop in a try.
Add a catch that catches the exception, but don't do anything with it.
Compile and run your program.
2. Now modify the body of the catch so that it prints a useful message (e.g., "Not a letter") followed by the exception.
Compile and run the program. Although it's useful to print the exception for debugging, when you're trying to smoothly
handle a condition that you don't consider erroneous you often don't want to. In your print statement, replace the
exception with the character that created the out of bounds index. Run the program again; much nicer!
// ****************************************************************
// CountLetters.java
//
// Reads a words from the standard input and prints the number of
// occurrences of each letter in that word.
//
// ****************************************************************
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
//print frequencies
System.out.println();
for (int i=0; i < counts.length; i++)
if (counts [i] != 0)
System.out.println((char)(i +'A') + ": " + counts[i]);
Save ParseInts to your directory and compile and run it. If you give it the input
10 20 30 40
it should print
Try some other inputs as well. Now try a line that contains both integers and other values, e.g.,
You should get a NumberFormatException when it tries to call Integer.parseInt on "We", which is not an integer. One way
around this is to put the loop that reads inside a try and catch the NumberFormatException but not do anything with it. This
way if it's not an integer it doesn't cause an error; it goes to the exception handler, which does nothing. Do this as follows:
Modify the program to add a try statement that encompasses the entire while loop. The try and opening { should go
before the while, and the catch after the loop body. Catch a NumberFormatException and have an empty body for the
catch.
Compile and run the program and enter a line with mixed integers and other values. You should find that it stops
summing at the first non-integer, so the line above will produce a sum of 0, and the line "1 fish 2 fish" will produce a
sum of 1. This is because the entire loop is inside the try, so when an exception is thrown the loop is terminated. To
make it continue, move the try and catch inside the loop. Now when an exception is thrown, the next statement is the
next iteration of the loop, so the entire line is processed. The dogs-and-cats input should now give a sum of 3, as should
the fish input.
import java.util.Scanner;
while (scanLine.hasNext())
{
val = Integer.parseInt(scanLine.next());
sum += val;
}
System.out.println("The sum of the integers on this line is " + sum);
}
1. Returning 1 as the factorial of any negative integer is not correct—mathematically, the factorial function is not defined
for negative integers. To correct this, you could modify your factorial method to check if the argument is negative, but
then what? The method must return a value, and even if it prints an error message, whatever value is returned could be
misconstrued. Instead it should throw an exception indicating that something went wrong so it could not complete its
calculation. You could define your own exception class, but there is already an exception appropriate for this situation—
IllegalArgumentException, which extends RuntimeException. Modify your program as follows:
Modify the header of the factorial method to indicate that factorial can throw an IllegalArgumentException.
Modify the body of factorial to check the value of the argument and, if it is negative, throw an
IllegalArgumentException. Note that what you pass to throw is actually an instance of the
IllegalArgumentException class, and that the constructor takes a String parameter. Use this parameter to be specific
about what the problem is.
Compile and run your Factorials program after making these changes. Now when you enter a negative number an
exception will be thrown, terminating the program. The program ends because the exception is not caught, so it is
thrown by the main method, causing a runtime error.
Modify the main method in your Factorials class to catch the exception thrown by factorial and print an appropriate
message, but then continue with the loop. Think carefully about where you will need to put the try and catch.
2. Returning a negative number for values over 16 also is not correct. The problem is arithmetic overflow—the factorial is
bigger than can be represented by an int. This can also be thought of as an IllegalArgumentException—this factorial
method is only defined for arguments up to 16. Modify your code in factorial to check for an argument over 16 as well
as for a negative argument. You should throw an IllegalArgumentException in either case, but pass different messages to
the constructor so that the problem is clear.
// ****************************************************************
// Factorials.java
//
// Reads integers from the user and prints the factorial of each.
//
// ****************************************************************
import java.util.Scanner;
• Remember that you can create a Scanner from a File object, which you can create from the String representing the
filename.
• The Scanner constructor that takes a File may throw a FileNotFoundException -- this is how you will know if the
file does not exist. Think carefully about how to use the try/catch structure in combination with a loop that asks for a
new filename if the current file does not exist.
• Remember that the scope of a variable declared inside a try is the try itself -- it does not extend to the following
code. Furthermore, the compiler knows that an initialization that occurs inside a try may or may not get executed, as
the try may be thrown out of first. So any variable that you will want to use both in and after the try must be
declared and initialized before the try.
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
The program should compute the GPA (grade point or quality point average) for each student (the total quality points divided
by the number of semester hours) then write the student information to the output file if that student should be put on
academic warning. A student will be on warning if he/she has a GPA less than 1.5 for students with fewer than 30 semester
hours credit, 1.75 for students with fewer than 60 semester hours credit, and 2.0 for all other students. The file Warning.java
contains a skeleton of the program. Do the following:
1. Set up a Scanner object scan from the input file and a PrintWriter outFile to the output file inside the try clause (see the
comments in the program). Note that you’ll have to create the PrintWriter from a FileWriter, but you can still do it in a
single statement.
2. Inside the while loop add code to read and parse the input—get the name, the number of credit hours, and the number of
quality points. Compute the GPA, determine if the student is on academic warning, and if so write the name, credit
hours, and GPA (separated by spaces) to the output file.
3. After the loop close the PrintWriter.
4. Think about the exceptions that could be thrown by this program:
• A FileNotFoundException if the input file does not exist
• A NumberFormatException if it can’t parse an int or double when it tries to – this indicates an error in the input
file format
• An IOException if something else goes wrong with the input or output stream
Add a catch for each of these situations, and in each case give as specific a message as you can. The program will
terminate if any of these exceptions is thrown, but at least you can supply the user with useful information.
5. Test the program. Test data is in the file students.dat. Be sure to test each of the exceptions as well.
// ****************************************************************************
// Warning.java
//
// Reads student data from a text file and writes data to another text file.
// ****************************************************************************
import java.util.Scanner;
import java.io.*;
while ()
{
// Get the credit hours and quality points and
// determine if the student is on warning. If so,
// write the student data to the output file.
}
}
students.dat
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
Wood 100 400
Street 33 57.4
Taylor 83 190
Davis 110 198
Smart 75 292.5
Bird 84 168
Summers 52 83.2
1. Add mnemonics to the buttons so that the user can move the circle by pressing the ALT-l, ALT-r, ALT-u, or ALT-d
keys.
2. Add tooltips to the buttons that indicate what happens when the button is pressed, including how far it is moved.
3. When the circle gets all the way to an edge, disable the corresponding button. When it moves back in, enable the button
again. Note that you will need instance variables (instead of local variables in the constructor) to hold the buttons and the
panel size to make them visible to the listener. Bonus: In most cases the circle won't hit the edge exactly; check for this
(e.g., x<0) and adjust the coordinates so it does.
// ******************************************************************
// MoveCircle.java
//
// Uses CirclePanel to display a GUI that lets the user move
// a circle by pressing buttons.
// ******************************************************************
import java.awt.*;
import javax.swing.*;
frame.getContentPane().add(new CirclePanel(400,300));
frame.setVisible(true);
}
}
//---------------------------------------------------------------
// Set up circle and buttons to move it.
//---------------------------------------------------------------
public CirclePanel(int width, int height)
{
// Set coordinates so circle starts in middle
x = (width/2)-(CIRCLE_SIZE/2);
y = (height/2)-(CIRCLE_SIZE/2);
c = Color.green;
//---------------------------------------------------------------
// Draw circle on CirclePanel
//---------------------------------------------------------------
public void paintComponent(Graphics page)
{
page.setColor(c);
page.fillOval(x,y,CIRCLE_SIZE,CIRCLE_SIZE);
}
//---------------------------------------------------------------
// Class to listen for button clicks that move circle.
//---------------------------------------------------------------
private class MoveListener implements ActionListener
{
private int dx;
private int dy;
//---------------------------------------------------------------
// Parameters tell how to move circle at click.
//---------------------------------------------------------------
public MoveListener(int dx, int dy)
{
this.dx = dx;
this.dy = dy;
}
//---------------------------------------------------------------
// Change x and y coordinates and repaint.
//---------------------------------------------------------------
public void actionPerformed(ActionEvent e)
{
x += dx;
y += dy;
repaint();
}
}
}
1. CurrencyPanel currently contains only two components—a JLabel for the title and a JLabel to display the result of the
calculations. It also contains two parallel arrays—one is an array of currency names (an array of strings) and the other an
array of corresponding exchange rates (the value of one unit of the currency in U.S. Dollars). Compile and run the
program to see what it looks like (not much!!).
2. Add a combo box to let the user select the currency. The argument to the constructor should be the array of names of the
currencies. Note that the first currency name is actually an instruction to the user so there is no need to have an additional
label.
3. Modify actionPerformed in ComboListener so that index is set to be the index of the selected item.
4. Test what you have so far. It should show what one unit of the given currency is in U.S. dollars.
5. Now add a text field (and label) so the user can enter the cost of an item in the selected currency. You need to update the
ComboListener so that it gets this value from the textfield and computes and displays the equivalent amount in dollars.
6. Test your program.
7. Modify the layout to create a more attractive GUI.
// ***********************************************************************
// CurrencyConverter.java
//
// Computes the dollar value of the cost of an item in another currency.
// ***********************************************************************
import java.awt.*;
import javax.swing.*;
// ******************************************************************
// RatePanel.java
//
// Panel for a program that converts different currencies to
// U.S. Dollars
// ******************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// ------------------------------------------------------------
// Sets up a panel to convert cost from one of 6 currencies
// into U.S. Dollars. The panel contains a heading, a text
// field for the cost of the item, a combo box for selecting
// the currency, and a label to display the result.
// ------------------------------------------------------------
public RatePanel ()
{
JLabel title = new JLabel ("How much is that in dollars?");
title.setAlignmentX (Component.CENTER_ALIGNMENT);
title.setFont (new Font ("Helvetica", Font.BOLD, 20));
add (title);
add (result);
// ******************************************************
// Represents an action listener for the combo box.
// ******************************************************
private class ComboListener implements ActionListener
{
// --------------------------------------------------
// Determines which currency has been selected and
// the value in that currency then computes and
// displays the value in U.S. Dollars.
// --------------------------------------------------
public void actionPerformed (ActionEvent event)
{
int index = 0;
result.setText ("1 " + currencyName[index] +
" = " + rate[index] + " U.S. Dollars");
}
}
}
Proceed as follows:
1. Compile and run the program as it is. You should see a GUI that contains the components listed above but nothing
happens when you click on the button. Fix this.
2. Modify PrimePanel.java so that the text area for displaying the primes is in a scroll pane. To do this, keep your
JTextArea but create a JScrollPane from it, and add the scroll pane to the panel. (If you look at the JScrollPane
documentation on p. 834-835 you’ll see that one of the constructors takes a Component, in this case your JTextArea.)
Test your modification.
3. You should see that the scrollbars don’t appear unless the output is longer than the text area. The default is for the
scrollbars to appear only as needed. This can be changed by setting the scroll bar policy of the JScrollPane object. Use
the setVerticalScrollBarPolicy method of the JScrollPane class to specify that the vertical scroll bar should always be
displayed. The method takes an integer argument that represents the policy. The ScrollPaneConstants class has several
static integer constants for the policies. These include VERTICAL_SCROLLBAR_ALWAYS,
VERTICAL_SCROLLBAR_AS_NEEDED, VERTICAL_SCROLLBAR_NEVER. It should be clear which of these to
use as the parameter. Remember how to access static members of a class!
4. The code to generate the list of primes could be improved some. Two things that should be done are:
A exception should be caught if the user enters non-integer data. An appropriate message should be displayed in the
text area.
The loop that looks for divisors of the integer i should not go all the way up to i. Instead it should stop at the square
root of i (if a divisor hasn't been found by then there isn't one).
Make these modifications.
// *****************************************************************
// Primes.java
//
// Generates a list of primes less than or equal to the integer
// input by the user.
// *****************************************************************
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// ----------------------------------------------------------
// Sets up a panel with a heading, a labeled text field
// for the user to enter an integer, a button to trigger
// the calculation, and a text area to display the list
// of primes.
// ----------------------------------------------------------
public PrimePanel ()
{
JLabel heading = new JLabel ("Prime Number Listing");
heading.setFont (new Font("Helvetica", Font.BOLD, 30));
computeButton.addActionListener(new ButtonListener());
// *****************************************************************
// Represents a listener for the click of the button.
// *****************************************************************
public class ButtonListener implements ActionListener
{
// -----------------------------------------------------------
// Generates and displays a list of primes when the
// button is clicked.
// -----------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
String textNum = number.getText();
int num = Integer.parseInt (textNum);
String ans = "";
primeList.setText (ans);
}