Review Exercises

advertisement
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 1
Review Exercises
R15.1
A stream reads bytes. A reader reads characters.
R15.3
If you write to a file reader, there will be a compile-time error because input files don't support output
operations such as print. If you write to a random access file that was opened for reading only, there will
be an exception.
R15.5
If you open a read-only file for writing, an exception is thrown.
R15.7
To break the Caesar cipher, you can try all 25 keys (b...z) to decrypt the message. Look at the decryptions and
see which one of them corresponds to English text.
R15.9
ls -f /export/home/user (or dir c:\ /D for Windows)
javac Example.java
R15.11
If you try to save an object to a object stream and the object is not serializable, an exception is thrown..
R15.13
If you simply save the entire ArrayList, you do not have to save the number of elements. If you saved a
collection manually, you'd first have to write out the length, then all entries. When reading the collection back
in, you'd have to read in the length, then allocate sufficient storage, and then read and store all entries. It is
much simpler to just write and read the ArrayList and let the serialization mechanism worry about saving
and restoring the length and the entries.
R15.15
The file pointer denotes the current position in a random access file for reading and writing. You move it
with the seek method of the RandomAccessFile class. You get the current position with the
getFilePointer method. This is the number of bytes from the beginning of the file, as a long integer,
because files can be longer than 2GB (the longest length representable with an int).
R15.17
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 2
You get an exception if you try to move the file pointer past the end of the file. You can't move the file
pointer on System.in. It is not a RandomAccessFile, therefore a call to the seek method is a
compile-time error.
Programming Exercises
P15.1
FileCounter.java
import java.io.FileReader;
import java.io.IOException;
/**
A class to count the number characters, words, and lines in a file
*/
public class FileCounter
{
/**
Construct a FileCounter object
*/
public FileCounter()
{
chars = 0;
words = 0;
lines = 0;
}
/**
Read the input file and count the number
of words, characters, and lines
@param file the file to count
*/
public void read(FileReader reader)
throws IOException
{
boolean space = true;
boolean more = true;
while (more)
{
int ic = reader.read();
if (ic == -1) more = false;
else
{
chars++;
char c = (char)ic;
if (c == '\n')
{
lines++;
space = true;
}
else if (c == ' ' || c == '\r')
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 3
space = true;
else
{
if (space)
words++;
space = false;
}
}
}
}
/**
Gets the number of characters in a file
@return the number of characters
*/
public int getCharacterCount()
{
return chars;
}
/**
Gets the number of words in a file
@return the number of words
*/
public int getWordCount()
{
return words;
}
/**
Gets the number of lines in a file
@return the number of lines
*/
public int getLineCount()
{
return lines;
}
private int chars;
private int words;
private int lines;
}
ExP15_1.java
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 4
This class tests the FileCounter class
*/
public class ExP15_1
{
public static void main(String[] args)
{
String input = "";
try
{
boolean done = false;
while (!done)
{
try
{
input = JOptionPane.showInputDialog(
"Filename: ");
if (input.equals(""))
done = true;
}
catch (Exception ex)
{
System.exit(0);
}
FileReader fin = new FileReader(input);
FileCounter fileCounter = new FileCounter();
fileCounter.read(fin);
System.out.println(
fileCounter.getCharacterCount() + " chars, "
+ fileCounter.getWordCount() + " words, "
+ fileCounter.getLineCount() + " lines");
fin.close();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
P15.3
FrequencyCounter.java
import java.io.FileReader;
import java.io.IOException;
/**
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 5
A class to find the frequency of letters in a file
*/
public class FrequencyCounter
{
/**
Construct a FrequencyCounter object
*/
public FrequencyCounter()
{
total = 0;
}
/**
Reads the input file
@param reader the input file
*/
public void read(FileReader reader)
throws IOException
{
freqs = new int[LETTERS.length()];
boolean more = true;
while (more)
{
int ic = reader.read();
if (ic == -1)
more = false;
else
{
char ch = Character.toLowerCase((char)ic);
int i = LETTERS.indexOf(ch);
if (i >= 0)
{
freqs[i]++;
total++;
}
}
}
if (total == 0)
return;
}
/**
Gets the frequency of the specified letter
@param c the character to get frequency percentage
@return the frequency
*/
public double getFrequency(char c)
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 6
{
return 100.0 * freqs[LETTERS.indexOf(c)] / total;
}
private final String LETTERS = "abcdefghijklmnopqrstuvwxyz";
private int[] freqs;
private int total;
}
ExP15_3.java
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
This class tests the FrequencyCounter class
*/
public class ExP15_3
{
public static void main(String[] args)
{
try
{
String f = JOptionPane.showInputDialog(
"Filename: ");
FileReader fin = new FileReader(f);
FrequencyCounter fc = new FrequencyCounter();
String letters = "abcdefghijklmnopqrstuvwxyz";
fc.read(fin);
for (int i = 0; i < letters.length(); i++)
{
double freq = fc.getFrequency(letters.charAt(i));
System.out.println(letters.charAt(i)
+ ":" + freq + "%");
}
fin.close();
System.exit(0);
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 7
P15.5
PlayfairCipher.java
import
import
import
import
import
import
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;
java.io.File;
java.io.Reader;
java.io.Writer;
/**
A class to encrypt and decrypt files using the Playfair cipher
*/
public class PlayfairCipher
{
/**
Construct a PlayfairCipher object
@param aKey the Playfair key to use
*/
public PlayfairCipher(String aKey)
{
key = aKey;
keys = makeEncryptionKey(key);
}
/**
Encrypts or decrypts all characters in a file and sends
them to another file.
@param inFile the input file
@param outFile the output file
*/
public void processFile(File inFile, File outFile)
throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader(inFile);
out = new FileWriter(outFile);
process(in, out);
}
finally
{
if (in != null)
in.close();
if (out != null)
out.close();
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 8
}
}
/**
Encrypts or decrypts all characters in a reader and sends
them to a writer.
@param in the input reader
@param out the output writer
*/
public void process(Reader in, Writer out)
throws IOException
{
while (true)
{
int ic1 = in.read();
if (ic1 == -1)
return;
int ic2 = in.read();
if (ic2 == -1)
{
out.write(ic1);
return;
}
processKeys(out, (char)ic1, (char)ic2);
}
}
public void processKeys(Writer out, char a, char b)
throws IOException
{
int
int
int
int
r1
r2
c1
c2
=
=
=
=
-1;
-1;
-1;
-1;
a = Character.toLowerCase(a);
b = Character.toLowerCase(b);
if (a == 'j')
a = 'i';
if (b == 'j')
b = 'i';
for (int i = 0; i < keys.length; i++)
for (int j = 0; j < keys[i].length; j++)
{
if (keys[i][j] == a)
{
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 9
r1 = i;
c1 = j;
}
if (keys[i][j] == b)
{
r2 = i;
c2 = j;
}
}
if (r1 == -1 || r2 == -1)
/* one of them wasn't a letter */
{
out.write(a);
out.write(b);
}
else
{
out.write(keys[r1][c2]);
out.write(keys[r2][c1]);
}
}
/**
Makes an encryption key
@param k the encryption key
@return the encryption tableau
*/
public char[][] makeEncryptionKey(String k)
{
String in = k.toLowerCase() + LETTERS;
char[][] out = new char[5][5];
int i;
int row = 0;
int col = 0;
for (i = 0; i < in.length(); i++)
{
char s = in.charAt(i);
if (s == 'j')
s = 'i';
if (!found(out, s))
{
out[row][col] = s;
col++;
if (col == out[row].length)
{
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 10
row++;
col = 0;
}
}
}
return out;
}
/**
Determines if character is found
@param square the square matrix
@param s the character to find
@return true if character is found, false otherwise
*/
public boolean found(char[][] square, char s)
{
for (int i = 0; i < square.length; i++)
for (int j = 0; j < square[i].length; j++)
if (square[i][j] != '\0' && square[i][j] == s)
return true;
return false;
}
private static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";
private String key;
private char[][] keys;
}
Crypt.java
import java.io.File;
import java.io.IOException;
/**
This class tests the PlayfairCipher class
*/
public class Crypt
{
public static void main(String[] args)
{
boolean decrypt = false;
String key = null;
File infile = null;
File outfile = null;
if (args.length < 2 || args.length > 4)
{
System.out.println
("Usage: java Crypt [-d] [-kn] infile outfile");
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 11
System.exit(1);
}
try
{
int i;
for (i = 0; i < args.length; i++)
{
if (args[i].substring(0, 1).equals("-"))
/* it is a command line option */
{
String option = args[i].substring(1, 2);
if (option.equals("d"))
decrypt = true;
else if (option.equals("k"))
key = args[i].substring(2);
}
else
{
if (infile == null)
{
infile = new File(args[i]);
}
else if (outfile == null)
{
outfile = new File(args[i]);
}
}
}
if (infile == null || outfile == null || key == null)
{
System.out.println
("Usage: java Crypt [-d] [-kn] infile outfile");
System.exit(1);
}
PlayfairCipher cipher = new PlayfairCipher(key);
cipher.processFile(infile, outfile);
}
catch (IOException e)
{
System.out.println(e);
}
}
}
P15.7
Solutions Manual: Chapter 15
CatFiles.java
Big Java, by Cay Horstmann 12
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
/**
This class concatenates contents of files into one file
*/
public class CatFiles
{
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: CatFiles sourcefile1 sourcefile2 .
. . targetfile");
return;
}
try
{
FileWriter out = new FileWriter(args[args.length - 1]);
for (int i = 0; i < args.length - 1; i++)
{
FileReader in = new FileReader(args[i]);
boolean more = true;
while (more)
{
int ic = in.read();
if (ic == -1) more = false;
else out.write(ic);
}
in.close();
}
out.close();
}
catch (IOException exception)
{
System.out.println(exception);
}
}
}
P15.9
SpellChecker.java
import
import
import
import
java.io.IOException;
java.io.FileReader;
java.io.BufferedReader;
java.util.ArrayList;
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 13
/**
A class to check the spelling of all words in a file
*/
public class SpellChecker
{
/**
Construct a SpellingCheck object
@param aFileName the name of the file
*/
public SpellChecker(String wordFileName)
throws IOException
{
filename = wordFileName;
BufferedReader in = new BufferedReader(
new FileReader(filename));
wordsList = new ArrayList();
boolean more = true;
while (more)
{
String w = in.readLine();
if (w == null)
more = false;
else
wordsList.add(w.toLowerCase());
}
in.close();
}
/**
Checks if a word is in the word list
@param word the word to check for
@return true if word was found, false otherwise
*/
public boolean check(String word)
{
boolean isFound = false;
for (int i = 0; i < wordsList.size();i++)
{
if (word.equals(wordsList.get(i)))
isFound = true;
}
return isFound;
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 14
private String filename;
private ArrayList wordsList;
}
SpellingCheck.java
import
import
import
import
java.io.IOException;
java.io.FileReader;
java.io.BufferedReader;
java.util.ArrayList;
/**
A class to check the spelling of all words in a file
*/
public class SpellingCheck
{
/**
Construct a SpellingCheck object
@param aFileName the name of the file
*/
public SpellingCheck(String aFileName)
{
filename = aFileName;
}
/**
Reads in the words in a file
@return r an array of words in a file
*/
public String[] readWords() throws IOException
{
BufferedReader in = new BufferedReader(new
FileReader(filename));
ArrayList w = new ArrayList();
boolean more = true;
while (more)
{
String word = in.readLine();
if (word == null)
more = false;
else w.add(word.toLowerCase());
if (w.size() % 1000 == 0)
System.out.println(w.size());
}
in.close();
String[] r = new String[w.size()];
w.toArray(r);
return r;
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 15
/**
Find the words in a file
@param s the word to find
@param a the file containing all words
@return the location of the word in words file
*/
public int find(String s, String[] a)
{
return binarySearch(a, 0, a.length - 1, s);
}
/**
Performs a binary search of the words in a file
@param v the words file
@param from index to start from
@param to index to search until
@param a the word to search for
@return the location of the word in words file
*/
public int binarySearch(String[] v, int from,
int to, String a)
{
if (from > to)
return -1;
int mid = (from + to) / 2;
int diff = v[mid].compareTo(a);
if (diff == 0) /* v[mid] == a */
return mid;
else if (diff < 0) /* v[mid] < a */
return binarySearch(v, mid + 1, to, a);
else
return binarySearch(v, from, mid - 1, a);
}
private String filename;
}
ExP15_9.java
import
import
import
import
java.io.IOException;
java.io.FileReader;
java.io.BufferedReader;
java.util.StringTokenizer;
/**
This class tests the SpellChecker class
*/
public class ExP15_9
{
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 16
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: ExP15_9 file wordfile");
return;
}
try
{
SpellChecker sc = new SpellChecker(args[1]);
BufferedReader in = new BufferedReader(new
FileReader(args[0]));
boolean more = true;
while (more)
{
String line = in.readLine();
if (line == null)
more = false;
else
{
StringTokenizer tokenizer = new
StringTokenizer(line.toLowerCase());
while (tokenizer.hasMoreTokens())
{
String word = tokenizer.nextToken();
if (!sc.check(word))
System.out.println(word);
}
}
}
in.close();
}
catch (IOException exception)
{
System.out.println(exception);
}
}
}
P15.11
ExP15_11.java
import java.io.IOException;
/**
A class to replace all tab characters to spaces
*/
public class ExP15_11
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 17
{
public static void main(String[] args)
{
int col = 0;
boolean done = false;
try
{
while (!done)
{
int ic = System.in.read();
if (ic == -1)
done = true;
else
{
char ch = (char)ic;
if (ch == '\n' || ch == '\r')
col = 0;
else if (ch == '\t')
{
boolean done2 = false;
while (!done2)
{
System.out.print(" ");
col++;
if (col % TABS == 0)
done2 = true;
}
}
else
{
System.out.print(ch);
col++;
}
}
}
}
catch(IOException e)
{
System.out.println("Input/Output Exception " + e);
}
}
public static final int TABS = 3;
}
P15.13
CarData.java
import java.util.ArrayList;
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 18
import java.io.Serializable;
/**
A data set that contains an array list of cars.
*/
public class CarData implements Serializable
{
/**
Constructs a CarData object.
*/
public CarData()
{
data = new ArrayList();
}
/**
Sets the car.
@param x the x coordinate
@param y the y coordinate
*/
public void add(int x, int y)
{
Car c = new Car(x, y);
data.add(c);
}
/**
Returns the size of the array list.
@return size of array list.
*/
public int size()
{
return data.size();
}
/**
Removes all cars of the array list.
*/
public void clear()
{
data.clear();
}
/**
Gets a car.
@param n the index to the car.
@return the car with the given index.
*/
public Car get(int n)
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 19
{
return (Car)data.get(n);
}
private ArrayList data;
}
CarPanel.java
import
import
import
import
import
import
import
java.awt.Dimension;
java.awt.Graphics;
java.awt.Graphics2D;
javax.swing.JPanel;
java.awt.event.MouseAdapter;
java.awt.event.MouseEvent;
java.io.Serializable;
public class CarPanel extends JPanel implements Serializable
{
public CarPanel()
{
data = new CarData();
setPreferredSize(
new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
class ClickListener extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
data.add(x, y);
repaint();
}
};
addMouseListener(new ClickListener());
}
/**
Gets the car data
@return the car data
*/
public CarData getCarData()
{
return data;
}
/**
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 20
Sets the car data
@param d the new car data
*/
public void setCarData(CarData d)
{
data = d;
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i < data.size(); i++)
{
Car c = data.get(i);
c.draw(g2);
}
}
private CarData data;
private final int PANEL_WIDTH = 300;
private final int PANEL_HEIGHT = 300;
}
Car.java
import
import
import
import
import
import
java.awt.Graphics2D;
java.awt.geom.Ellipse2D;
java.awt.geom.Line2D;
java.awt.geom.Point2D;
java.awt.geom.Rectangle2D;
java.io.Serializable;
/**
A car shape that can be positioned anywhere on the screen.
*/
public class Car implements Serializable
{
/**
Constructs a car with a given top left corner
@param x the x coordinate of the top left corner
@param y the y coordinate of the top left corner
*/
public Car(double x, double y)
{
xLeft = x;
yTop = y;
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 21
/**
Draws the car
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
Rectangle2D.Double body
= new Rectangle2D.Double(xLeft, yTop + 10, 60, 10);
Ellipse2D.Double frontTire
= new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10);
Ellipse2D.Double rearTire
= new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10);
// the bottom of the front windshield
Point2D.Double r1
= new Point2D.Double(xLeft + 10, yTop + 10);
// the front of the roof
Point2D.Double r2
= new Point2D.Double(xLeft + 20, yTop);
// the rear of the roof
Point2D.Double r3
= new Point2D.Double(xLeft + 40, yTop);
// the bottom of the rear windshield
Point2D.Double r4
= new Point2D.Double(xLeft + 50, yTop + 10);
Line2D.Double frontWindshield
= new Line2D.Double(r1, r2);
Line2D.Double roofTop
= new Line2D.Double(r2, r3);
Line2D.Double rearWindshield
= new Line2D.Double(r3, r4);
g2.draw(body);
g2.draw(frontTire);
g2.draw(rearTire);
g2.draw(frontWindshield);
g2.draw(roofTop);
g2.draw(rearWindshield);
}
private double xLeft;
private double yTop;
}
MenuFrame.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Solutions Manual: Chapter 15
import
import
import
import
import
import
import
import
import
import
import
import
import
import
Big Java, by Cay Horstmann 22
java.util.Random;
java.util.ArrayList;
javax.swing.JFrame;
javax.swing.JMenu;
javax.swing.JMenuBar;
javax.swing.JMenuItem;
javax.swing.JFileChooser;
java.io.Serializable;
java.io.File;
java.io.IOException;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.ObjectInputStream;
java.io.ObjectOutputStream;
/**
This frame has a menu with commands to load and save a car file.
*/
class MenuFrame extends JFrame implements Serializable
{
/**
Constructs the frame.
*/
public MenuFrame()
{
// add drawing panel to content pane
panel = new CarPanel();
getContentPane().add(panel, BorderLayout.CENTER);
pack();
// construct menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
}
/**
Creates the File menu.
@return the menu
*/
public JMenu createFileMenu()
{
JMenu menu = new JMenu("File");
menu.add(createFileNewItem());
menu.add(createFileOpenItem());
menu.add(createFileSaveItem());
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 23
menu.add(createFileExitItem());
return menu;
}
/**
Creates the File->New menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileNewItem()
{
JMenuItem item = new JMenuItem("New");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
panel.setCarData(new CarData());
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Open menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileOpenItem()
{
JMenuItem item = new JMenuItem("Open");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) ==
JFileChooser.CANCEL_OPTION) return;
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(chooser.getSelectedFile()));
CarData data = (CarData)in.readObject();
in.close();
panel.setCarData(data);
}
catch (IOException e)
{
System.out.println(e);
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 24
}
catch (ClassNotFoundException ex)
{
System.out.println(ex);
}
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Save menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileSaveItem()
{
JMenuItem item = new JMenuItem("Save");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) ==
JFileChooser.CANCEL_OPTION) return;
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(chooser.getSelectedFile()));
out.writeObject(panel.getCarData());
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
repaint();
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Exit menu item and sets its action listener.
@return the menu item
*/
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 25
public JMenuItem createFileExitItem()
{
JMenuItem item = new JMenuItem("Exit");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
private CarPanel panel;
}
ExP15_13.java
import javax.swing.JFrame;
public class ExP15_13
{
public static void main(String[] args)
{
JFrame frame = new MenuFrame();
frame.setTitle("ExP15_13");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
P15.15
Coin.java
import java.io.Serializable;
/**
A coin with a monetary value.
*/
public class Coin implements Serializable
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 26
value = aValue;
name = aName;
}
/**
Gets the coin value.
@return the value
*/
public double getValue()
{
return value;
}
/**
Gets the coin name.
@return the name
*/
public String getName()
{
return name;
}
public boolean equals(Object otherObject)
{
Coin other = (Coin)otherObject;
return name.equals(other.name)
&& value == other.value;
}
private double value;
private String name;
}
Purse.java
import java.io.Serializable;
import java.util.ArrayList;
/**
A purse holds collection of coins.
*/
public class Purse implements Serializable
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 27
/**
Add a coin to the purse.
@param aCoin the coin to add
*/
public void add(Coin aCoin)
{
coins.add(aCoin);
}
/**
Get the total value of the coins in the purse.
@return the sum of all coin values
*/
public double getTotal()
{
double total = 0;
for (int i = 0; i < coins.size(); i++)
{
Coin aCoin = (Coin)coins.get(i);
total = total + aCoin.getValue();
}
return total;
}
private ArrayList coins;
}
PurseFrame.java
import
import
import
import
import
java.awt.*;
java.awt.event.*;
java.io.*;
javax.swing.*;
java.text.*;
/**
A frame with a menu for loading and saving a purse,
and for adding coins.
*/
public class PurseFrame extends JFrame
{
/**
Constructs the label and menus.
*/
public PurseFrame()
{
purse = new Purse();
label = new JLabel();
setLabelText();
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 28
getContentPane().add(label, BorderLayout.CENTER);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(createFileMenu());
bar.add(createAddMenu());
pack();
}
/**
Creates the File menu.
@return the menu
*/
public JMenu createFileMenu()
{
JMenu menu = new JMenu("File");
menu.add(createFileOpenItem());
menu.add(createFileSaveItem());
menu.add(createFileExitItem());
return menu;
}
/**
Creates the Add menu.
@return the menu
*/
public JMenu createAddMenu()
{
JMenu menu = new JMenu("Add");
menu.add(createAddItem(new Coin(NICKEL_VALUE, "nickel")));
menu.add(createAddItem(new Coin(DIME_VALUE, "dime")));
menu.add(createAddItem(new Coin(QUARTER_VALUE, "quarter")));
return menu;
}
/**
Creates the File->Open menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileOpenItem()
{
JMenuItem item = new JMenuItem("Open");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser chooser = new JFileChooser();
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 29
if (chooser.showOpenDialog(null) ==
JFileChooser.CANCEL_OPTION) return;
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(chooser.getSelectedFile()));
purse = (Purse)in.readObject();
in.close();
setLabelText();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Save menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileSaveItem()
{
JMenuItem item = new JMenuItem("Save");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) ==
JFileChooser.CANCEL_OPTION) return;
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(chooser.getSelectedFile()));
out.writeObject(purse);
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 30
repaint();
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Exit menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createFileExitItem()
{
JMenuItem item = new JMenuItem("Exit");
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Creates the File->Exit menu item and sets its action listener.
@return the menu item
*/
public JMenuItem createAddItem(final Coin coin)
{
JMenuItem item = new JMenuItem(coin.getName());
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
purse.add(coin);
setLabelText();
}
}
ActionListener listener = new MenuItemListener();
item.addActionListener(listener);
return item;
}
/**
Sets the label text to the purse total.
Solutions Manual: Chapter 15
Big Java, by Cay Horstmann 31
*/
public void setLabelText()
{
double totalValue = purse.getTotal();
NumberFormat formatter = NumberFormat.getCurrencyInstance();
label.setText("The total value is " +
formatter.format(totalValue));
}
private
private
private
private
private
JLabel label;
Purse purse;
static double NICKEL_VALUE = 0.05;
static double DIME_VALUE = 0.1;
static double QUARTER_VALUE = 0.25;
}
PurseTest.java
import javax.swing.JFrame;
/**
This program tests serialization of a Purse object.
*/
public class PurseTest
{
public static void main(String[] args)
{
JFrame frame = new PurseFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
Download