Академический Документы
Профессиональный Документы
Культура Документы
Review Exercises
R13.1
An index is an integer value which represents a position in an array list.
The bounds of an array list is from 0 to 1 less than the size of the array list.
A bounds error occurs when either the minimum or maximum index value is exceeded in an attempted access of an
array list element. Anything less than 0 or greater than or equal to the array list size will produce a bounds error.
R13.2
import java.util.ArrayList;
R13.3
import java.util.ArrayList;
if (c.getValue()
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 2
R13.4
import java.util.ArrayList;
import java.util.StringTokenizer;
while (t.hasMoreTokens())
stringList.add(t.nextToken());
R13.5
1 2 3 4 5 6 7 8 9 10
int[] a = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
R13.6
int[] a = new int[10];
Random generator = new Random();
for (int i = 0 i < a.length; i++)
a[i] = 1 + generator.nextInt(100);
R13.7
There is a bounds error. The index of the for loop begins at 1 - skipping the first element of the array - and ends with
10 - which is one past the end and a fatal error.
One remedy is to adjust the bounds for i:
for (int i = 0; i < 10; i++) data[i] = (i + 1) * (i + 1);
Another remedy is to adjust the array index:
for (int i = 1; i <= 10; i++) data[i - 1] = i * i;
R13.8
public class ExR13_8
{
public static void main(String[] args)
{
int[] data = new int[20];
R13.9
A useful method that has an array of integers as a parameter that is not modified :
A method that computes the maximum value of the numbers stored in an array
A useful method that has an array of integers as a parameter that is modified:
A method that sorts the numbers in an array
A useful method that has an array of integers as a return value:
A method that returns a sorted copy of an input array, without modifying the parameter array
R13.10
Change each employee's salary by add a bonus of $1000 per employee. This method keeps the order of the
employees unchanged but modifies individual elements.
Sort the employees by name in the Employee array list. This method rearranges the order of the employees but
keeps each element unchanged.
R13.11
Parallel arrays are two or more arrays of equivalent length in which corresponding elements are logically related.
Parallel arrays are indications of poor programming because items that are conceptually related are not represented
together. This makes it more difficult to use private data, and to change the data representation.
To avoid parallel arrays, find a concept that describes the related elements and make it into a class having instance
variables corresponding to the separate array elements. Then, make a single array of the new class type.
R13.12
Test that two arrays contain the same elements in the same order
If the two arrays have the same size, in a while loop, test that each successive pair of elements is equivalent.
Return false at the first nonequivalence, otherwise return true, meaning they are equal.
if (a1.length == a2.length) { int
i = 0; while (i < a1.size()) { if (a1[i] == a2[i]) // or
a1[i].equals(a2[i]))
if the arrays contain objects i++; else return false; // they aren't
equal } return
true; } else return false; // they aren't equal
Copy one array to another
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 4
Make a new array of same size and type as the first, then in a for loop bounded by the array size, assign each
successive member of the original array to the new one. Or, use System.arraycopy
Fill an array with zeroes, overwriting all elements in it.
In a for loop bounded by the size of the array, assign 0 to each element in the array.
Remove all elements from an array
Use a for loop to go through all the elements in the array list in reverse orde r, removing each one it visits by
using remove(i).
R13.13
All elements of an array are of the same type true
Array subscripts must be integers true
false, for example main(String[]
Arrays cannot contain strings as elements
args)
Arrays cannot use strings as subscripts true
Parallel arrays must have equal length. true (in order to be parallel)
Two-dimensional arrays always have the same number
false (square matrices, however do)
of rows as columns
Two parallel arrays can be replaced by a two- false (the array elements might be of
dimensional array different type)
Elements of different columns in a matrix can have
false
different types
Elements in an array list can have different types true
R13.14
A method cannot return a two-dimensional array false
A method cannot change the size of an array parameter true
A method can change the length of an array list that is passed as a
true
parameter
An array list can hold values of any type false
Programming Exercises
P13.1
Bank.java
import java.util.ArrayList;
/**
A bank deposits and withdraws money for its customers
*/
public class Bank
{
/**
Construct a Bank object
*/
public Bank()
{
accountList = new ArrayList();
}
/**
Add an account to the bank
@param initialBalance the initial balance of this account
*/
public void addAccount(double initialBalance)
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 5
accountList.add(new BankAccount(initialBalance));
}
/**
Deposit an amount to a particular account
@param account the account to deposit money into
@param amount the amound to deposit
*/
public void deposit(int account, double amount)
{
BankAccount acct = (BankAccount)accountList.get(account);
acct.deposit(amount);
}
/**
Withdraw an amount from a particular account
@param account the account to withdraw money from
@param amount the amound to withdraw
*/
public void withdraw(int account, double amount)
{
BankAccount acct = (BankAccount)accountList.get(account);
acct.withdraw(amount);
}
/**
Gets the balance of a particular account
@param account the account to get the balance from
@return balance the balance of the account
*/
public double getBalance(int account)
{
BankAccount acct = (BankAccount)accountList.get(account);
return acct.getBalance();
}
BankAccount.java
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
/**
Constructs a bank account with a zero balance
*/
public BankAccount()
{
balance = 0;
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 6
/**
Constructs a bank account with a given balance
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
balance = balance + amount;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
balance = balance - amount;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
/**
Transfers money from the bank account to another account
@param other the other account
@param amount the amount to transfer
*/
public void transfer(BankAccount other, double amount)
{
withdraw(amount);
other.deposit(amount);
}
ExP13_1.java
/**
This program tests the Bank class
*/
public class ExP13_1
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 7
{
public static void main(String[] args)
{
Bank bank = new Bank();
bank.addAccount(1000);
bank.addAccount(2000);
bank.addAccount(3000);
bank.addAccount(10000);
int dannysAccount = 0;
int sallysAccount = 1;
int harrysAccount = 2;
int jerrysAccount = 3;
bank.deposit(dannysAccount, 200);
bank.withdraw(sallysAccount, 500);
bank.deposit(harrysAccount, 1000);
bank.withdraw(jerrysAccount, 7000);
System.out.println(
"Danny's Account Balance: " + bank.getBalance(dannysAccount));
System.out.println(
"Sally's Account Balance: " + bank.getBalance(sallysAccount));
System.out.println(
"Harry's Account Balance: " + bank.getBalance(harrysAccount));
System.out.println(
"Jerry's Account Balance: " + bank.getBalance(jerrysAccount));
}
}
P13.2
Coin.java
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
value = aValue;
name = aName;
}
/**
Gets the coin value.
@return the value
*/
public double getValue()
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 8
return value;
}
/**
Gets the coin name.
@return the name
*/
public String getName()
{
return name;
}
/**
Displays the string representation of the object
@return output the string representation of the coin
*/
public String toString()
{
return "Coin[value="
+ value + ",name=" + name + "]";
}
private double value;
private String name;
}
Purse.java
import java.util.ArrayList;
/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
/**
Add a coin to the purse.
@param aCoin the coin to add
*/
public void add(Coin aCoin)
{
coins.add(aCoin);
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 9
/**
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;
}
/**
Displays the string representation of the object
@return output the string representation of coins
*/
public String toString()
{
String output = "Purse[";
ExP13_2.java
/**
This class tests the Purse class.
*/
public class ExP13_2
{
public static void main(String[] args)
{
Purse p = new Purse();
p.add(new Coin(0.25, "Quarter"));
p.add(new Coin(0.10, "Dime"));
p.add(new Coin(0.05, "Nickel"));
p.add(new Coin(0.10, "Dime"));
System.out.println(p.toString());
}
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 10
P13.3
Coin.java
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
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;
}
Purse.java
import java.util.ArrayList;
/**
A purse holds a collection of coins.
*/
public class Purse
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 11
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
/**
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;
}
/**
Reverses the elements in the purse
*/
public void reverse()
{
int i = 0;
int j = coins.size() - 1;
while (i < j)
{
Object temp = coins.get(i);
coins.set(i, coins.get(j));
coins.set(j, temp);
i++;
j--;
}
}
/**
Displays the string representation of the object
@return output the string representation of coins
*/
public String toString()
{
String output = "Purse[";
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 12
ExP13_3.java
/**
This class tests the Purse class.
*/
public class ExP13_3
{
public static void main(String[] args)
{
Purse p = new Purse();
p.add(new Coin(0.25, "Quarter"));
p.add(new Coin(0.10, "Dime"));
p.add(new Coin(0.05, "Nickel"));
p.add(new Coin(0.10, "Dime"));
System.out.println(p.toString());
p.reverse();
System.out.println(p.toString());
}
}
P13.4
Coin.java
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
value = aValue;
name = aName;
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 13
/**
Gets the coin value.
@return the value
*/
public double getValue()
{
return value;
}
/**
Gets the coin name.
@return the name
*/
public String getName()
{
return name;
}
Purse.java
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
/**
Add a coin to the purse.
@param aCoin the coin to add
*/
public void add(Coin aCoin)
{
coins.add(aCoin);
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 14
/**
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;
}
/**
Transfer the coins from one purse to another
@param other the other purse
*/
public void transfer(Purse other)
{
for (int i = 0; i < other.coins.size(); i++)
{
Coin c = (Coin)other.coins.get(i);
add(c);
}
other.coins.clear();
}
ExP13_4.java
/**
This class tests the Purse class.
*/
public class ExP13_4
{
public static void main(String[] args)
{
Purse a = new Purse();
a.add(new Coin(0.25, "Quarter"));
a.add(new Coin(0.10, "Dime"));
a.add(new Coin(0.05, "Nickel"));
a.add(new Coin(0.10, "Dime"));
a.transfer(b);
System.out.println(a.toString());
System.out.println(b.toString());
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 15
}
P13.5
Coin.java
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
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;
}
Purse.java
import java.util.ArrayList;
/**
A purse holds a collection of coins.
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 16
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
/**
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;
}
/**
Determines if a purse has the same coins in the same
order as another purse
@param other the other purse
@return true if the two purses have the same coins in the
same order, false otherwise
*/
public boolean equals(Object other)
{
Purse p = (Purse)other;
for (int i = 0; i < coins.size(); i++)
{
if (!getCoin(i).equals(p.getCoin(i)))
return false;
}
return true;
}
/**
Helper method to retrieve a coin from a specific index
@param index the index of the coin to retrieve
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 17
@return a string containing the coin
*/
private String getCoin(int index)
{
Coin c = (Coin)coins.get(index);
return c.getName();
}
ExP13_5.java
/**
This class tests the Purse class.
*/
public class ExP13_5
{
public static void main(String[] args)
{
Purse a = new Purse();
a.add(new Coin(0.25, "Quarter"));
a.add(new Coin(0.10, "Dime"));
System.out.println(a.equals(b));
System.out.println(c.equals(d));
}
}
P13.6
Coin.java
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 18
public Coin(double aValue, String aName)
{
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;
}
Purse.java
import java.util.ArrayList;
/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
equalCoins = new ArrayList();
}
/**
Add a coin to the purse.
@param aCoin the coin to add
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 19
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;
}
P13.6
/**
Determines if a purse has the same coins in some order as another purse
@param other the other purse
@return true if the two purses have the same coins in some order, false
otherwise
*/
public boolean equals(Object other)
{
Purse p = (Purse)other;
return true;
}
/**
Counts the number of times the same coin is in
both purses
@param c the coin to examine
@return count the number of times the coin is in purse
*/
public int count(Coin c)
{
int count = 0;
for (int i = 0; i < coins.size(); i++)
{
Coin coin = (Coin)coins.get(i);
if (c.getName().equals(coin.getName()))
count++;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 20
}
return count;
}
ExP13_6.java
/**
This class tests the Purse class.
*/
public class ExP13_6
{
public static void main(String[] args)
{
Purse a = new Purse();
a.add(new Coin(0.25, "Quarter"));
a.add(new Coin(0.10, "Dime"));
a.add(new Coin(0.05, "Nickel"));
a.add(new Coin(0.10, "Dime"));
System.out.println(a.equals(b));
System.out.println(c.equals(d));
}
}
P13.7
Cloud.java
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 21
This class draws a cloud of circles
*/
public class Cloud
{
/**
Construct a Cloud object
*/
public Cloud()
{
points = new ArrayList();
}
/**
Add a point to the array list
@param aPoint the point to add
*/
public void add(Point2D.Double aPoint)
{
points.add(aPoint);
}
/**
Draws the cloud
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
for (int i = 0; i < points.size(); i++)
{
Point2D.Double p = (Point2D.Double)points.get(i);
Ellipse2D.Double e =
new Ellipse2D.Double(p.getX(), p.getY(), RADIUS, RADIUS);
g2.draw(e);
}
}
ExP13_7.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import java.awt.geom.Point2D;
/**
This applet displays a cloud of circles
*/
public class ExP13_7 extends Applet
{
public void paint(Graphics g)
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 22
Graphics2D g2 = (Graphics2D)g;
c.draw(g2);
}
}
P13.8
Polygon.java
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
A polygon is a closed curve made up from line segment
that join the corner points.
*/
/**
Adds a point of the polygon.
@param aPoint the point
*/
public void add(Point2D.Double aPoint)
{
points.add(aPoint);
}
/**
Draws the polygon.
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 23
{
for (int i = 0; i < points.size(); i++)
{
Point2D.Double from = (Point2D.Double)points.get(i);
Point2D.Double to = (Point2D.Double)points.get((i + 1) %
points.size());
g2.draw(new Line2D.Double(from, to));
}
}
ExP13_8.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
/**
This applet displays two polygons
*/
public class ExP13_8 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
square.draw(g2);
pentagon.draw(g2);
}
}
P13.9
Polygon.java
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.Graphics2D;
import java.util.ArrayList;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 24
/**
A polygon is a closed curve made up from line segment
that join the corner points.
*/
/**
Adds a point of the polygon.
@param aPoint the point
*/
public void add(Point2D.Double aPoint)
{
points.add(aPoint);
}
/**
Draws the polygon.
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
for (int i = 0; i < points.size(); i++)
{
Point2D.Double from = (Point2D.Double)points.get(i);
Point2D.Double to = (Point2D.Double)points.get((i + 1) %
points.size());
g2.draw(new Line2D.Double(from, to));
}
}
/**
Calculates the perimeter of a polygon
@return p the perimeter
*/
public double perimeter()
{
double p = 0;
int i;
for (i = 0; i < points.size(); i++)
{
Point2D.Double from = (Point2D.Double)points.get(i);
Point2D.Double to = (Point2D.Double)points.get((i + 1) %
points.size());
p = p + distance(from, to);
}
return p;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 25
}
/**
Helper method to calculate the distance between two points
@param p the point p
@param q the point q
@return distance between two points
*/
public static double distance(Point2D.Double p, Point2D.Double q)
{
double dx = p.getX() - q.getX();
double dy = p.getY() - q.getY();
return Math.sqrt(dx * dx + dy * dy);
}
/**
Calculates the area of a polygon
@return area of a polygon
*/
public double area()
{
double a = 0;
ExP13_9.java
import java.awt.geom.Point2D;
/**
This is a test class for Polygon
*/
public class ExP13_9
{
public static void main(String[] args)
{
ExP13.10
DataSet.java
/**
This class computes the average and alternating sum
of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set.
*/
public DataSet()
{
final int DATA_LENGTH = 100;
data = new double[DATA_LENGTH];
dataSize = 0;
}
/**
Adds a data value to the data set
@param x a data value
*/
public void add(double x)
{
if (dataSize >= data.length)
{
// make a new array of twice the size
double[] newData = new double[2 * data.length];
// copy over all elements from data to newData
System.arraycopy(data, 0, newData, 0, data.length);
// abandon the old array and store in data
// a reference to the new array
data = newData;
}
data[dataSize] = x;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 27
dataSize++;
}
/**
Gets the average of the added data.
@return the average or 0 if no data has been added
*/
public double getAverage()
{
if (dataSize == 0) return 0;
double sum = 0;
for (int i = 0; i < dataSize; i++)
sum = sum + data[i];
return sum / dataSize;
}
/**
Gets the alternating sum of the added data.
@return sum the sum of the alternating data.
*/
public double alternatingSum()
{
if (dataSize == 0) return 0;
double sum = 0;
for (int i = 0; i < dataSize; i++)
{
if (i % 2 == 0)
sum += data[i];
else
sum -= data[i];
}
return sum;
}
DataSetTest.java
/**
This program tests the DataSet class
*/
public class DataSetTest
{
public static void main(String[] args)
{
DataSet data = new DataSet();
data.add(1);
data.add(4);
data.add(9);
data.add(16);
data.add(9);
data.add(7);
data.add(4);
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 28
data.add(9);
data.add(11);
P13.11
PermutationGenerator.java
import java.util.Random;
/**
This class provides a method to generate permutations.
*/
public class PermutationGenerator
{
/**
Construct a PermutationGenerator object
*/
public PermutationGenerator()
{
generator = new Random();
}
/**
Gets the next permutation
@param n the maximum number in the permutation
@param r the array containing the permutations
*/
public int[] nextPermutation(int n)
{
int[] p = new int[n];
for (int i = 0; i < n; i++)
p[i] = i + 1;
int pSize = n;
int[] r = new int[n];
ExP13_11.java
/**
This is a test class for the PermutationGenerator class.
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 29
public class ExP13_11
{
public static void main(String[] args)
{
final int MAX_NUM = 10;
final int MAX_PERM = 10;
/**
Prints the permutations
@param a the array containing the permutations
*/
public static void print(int[] a)
{
for (int i = 0; i < a.length ; i++ )
{
System.out.print(" " + a[i]);
}
System.out.println();
}
}
P13.12
Chart.java
import java.util.ArrayList;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
/**
This class draws a stick chart
*/
public class Chart
{
/**
Constructs a Chart object
@param aWidth the applet width
@param aHeight the applet height
*/
public Chart(double aWidth, double aHeight)
{
width = aWidth;
height = aHeight;
data = new ArrayList();
}
/**
Adds the data value to the list
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 30
@param value the data value
*/
public void add(int value)
{
Integer num = new Integer(value);
data.add(num);
}
/**
Draws the stick chart
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
int i = 0;
double max = 0;
for (i = 0; i < data.size(); i++)
{
Integer wrapper = (Integer)data.get(i);
int x = wrapper.intValue();
if(max < x)
max = x;
}
double xleft = 0;
for (i = 0; i < data.size(); i++)
{
Integer wrapper = (Integer)data.get(i);
int x = wrapper.intValue();
double xright = xwidth * (i + 1) / data.size();
double y = yheight * x / max;
g2.draw(new Line2D.Double(
new Point2D.Double(xleft, yheight),
new Point2D.Double(xleft, yheight - y)));
xleft = xright;
}
}
ExP13_12.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
This applet displays a stick chart
*/
public class ExP13_12 extends Applet
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 31
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Chart c = new Chart(getWidth(), getHeight());
c.add(1);
c.add(3);
c.add(4);
c.add(3);
c.add(2);
c.add(5);
c.add(7);
c.draw(g2);
}
}
P13.13
BarChart.java
import java.util.ArrayList;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
This class draws a bar chart
*/
public class BarChart
{
/**
Constructs a BarChart object
@param aWidth the applet width
@param aHeight the applet height
*/
public BarChart(double aWidth, double aHeight)
{
width = aWidth;
height = aHeight;
data = new ArrayList();
}
/**
Adds the data value to the list
@param value the data value
*/
public void add(double value)
{
Double num = new Double(value);
data.add(num);
}
/**
Draws the bar chart
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 32
{
int i = 0;
double max = 0;
for (i = 0; i < data.size(); i++)
{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();
if(max < x)
max = x;
}
double xleft = 0;
Rectangle2D.Double bar =
new Rectangle2D.Double(xleft, yheight - barHeight,
barWidth, barHeight);
g2.draw(bar);
xleft = xright;
}
}
ExP13_13.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
This applet displays a bar chart
*/
public class ExP13_13 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
BarChart c = new BarChart(getWidth(), getHeight());
c.add(1.1);
c.add(3.6);
c.add(4.0);
c.add(3.7);
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 33
c.add(2.1);
c.add(2.7);
c.add(2.6);
c.draw(g2);
}
}
P13.14
BarChart.java
import java.util.ArrayList;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
This class draws a bar chart
*/
public class BarChart
{
/**
Constructs a BarChart object
@param aWidth the applet width
@param aHeight the applet height
*/
public BarChart(double aWidth, double aHeight)
{
width = aWidth;
height = aHeight;
data = new ArrayList();
}
/**
Adds the data value to the list
@param value the data value
*/
public void add(double value)
{
Double num = new Double(value);
data.add(num);
}
/**
Draws the bar chart
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
int i = 0;
double max = 0;
double min = 0;
for (i = 0; i < data.size(); i++)
{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();
if(max < x)
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 34
max = x;
if (min > x)
min = x;
}
double xleft = 0;
double ybase = yheight * max / (max - min);
if (x > 0)
{
Rectangle2D.Double bar =
new Rectangle2D.Double(xleft, ybase - y,
barWidth, Math.abs(y));
g2.draw(bar);
}
else
{
Rectangle2D.Double bar =
new Rectangle2D.Double(xleft, ybase,
barWidth, Math.abs(y));
g2.draw(bar);
}
xleft = xright;
}
}
ExP13_14.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
This applet displays a bar chart
*/
public class ExP13_14 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 35
BarChart c = new BarChart(getWidth(), getHeight());
c.add(1.1);
c.add(-3.6);
c.add(4.0);
c.add(3.7);
c.add(-2.1);
c.add(.7);
c.add(2.6);
c.draw(g2);
}
}
P13.15
PieChart.java
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
/**
This class draws a pie chart
*/
public class PieChart
{
/**
Constructs a PieChart object
@param aWidth the applet width
@param aHeight the applet height
*/
public PieChart(double aWidth, double aHeight)
{
width = aWidth;
height = aHeight;
data = new ArrayList();
}
/**
Adds the data value to the list
@param value the data value
*/
public void add(double value)
{
Double num = new Double(value);
data.add(num);
}
/**
Draws a pie chart
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
int i = 0;
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 36
double total = 0;
for (i = 0; i < data.size(); i++)
{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();
total += x;
}
double angle = 0;
for (i = 0; i < data.size(); i++)
{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();
angle += 2 * Math.PI * x / total;
Point2D.Double p
= new Point2D.Double(radius + radius * Math.cos(angle),
radius + radius * Math.sin(angle) );
g2.draw(new Line2D.Double(center, p));
}
}
ExP13_15.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
This applet displays a pie chart
*/
public class ExP13_15 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
PieChart p = new PieChart(getWidth(), getHeight());
p.add(1.1);
p.add(3.6);
p.add(4.0);
p.add(3.7);
p.add(2.1);
p.add(2.7);
p.add(2.6);
p.draw(g2);
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 37
}
}
P13.16
TicTacToe.java
/**
A 3 x 3 Tic-Tac-Toe board.
*/
public class TicTacToe
{
/**
Constructs an empty board.
*/
public TicTacToe()
{
board = new String[ROWS][COLUMNS];
/**
Sets a field in the board. The field must be unoccupied.
@param i the row index
@param j the column index
@param player the player ("x" or "o")
*/
public void set(int i, int j, String player)
{
if (!board[i][j].equals(" "))
throw new IllegalArgumentException("Position occupied");
board[i][j] = player;
}
/**
Creates a string representation of the board such as
|x o|
| x |
| o|
@return the string representation
*/
public String toString()
{
String r = "";
for (int i = 0; i < ROWS; i++)
{
r = r + "|";
for (int j = 0; j < COLUMNS; j++)
r = r + board[i][j];
r = r + "|\n";
}
return r;
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 38
/**
Gets the winner
@return the winner
*/
public String getWinner()
{
// check rows
for (int i = 0; i < board.length; i++)
{
String p = board[i][0];
boolean same = true;
for (int j = 1; j < board.length && same; j++)
{
if (!p.equals(board[i][j]))
same = false;
}
if (same)
return p;
}
// check columns
for (int i = 0; i < board.length; i++)
{
String p = board[0][i];
boolean same = true;
for (int j = 1; j < board.length && same; j++)
{
if (!p.equals(board[j][i]))
same = false;
}
if (same)
return p;
}
// check diagonals
String p = board[0][0];
boolean same = true;
for (int j = 1; j < board.length && same; j++)
{
if (!p.equals(board[j][j]))
same = false;
}
if (same)
return p;
p = board[0][board.length - 1];
same = true;
TicTacToeTest.java
import javax.swing.JOptionPane;
/**
This program tests the TicTacToe class by prompting the
user to set positions on the board and printing out the
result.
*/
public class TicTacToeTest
{
public static void main(String[] args)
{
String player = "x";
TicTacToe game = new TicTacToe();
while (true)
{
System.out.println(game); // calls game.toString()
String input = JOptionPane.showInputDialog(
"Row for " + player + " (Cancel to exit)");
if (input == null)
System.exit(0);
int row = Integer.parseInt(input);
input = JOptionPane.showInputDialog(
"Column for " + player);
int column = Integer.parseInt(input);
game.set(row, column, player);
if (player == "x")
player = "o";
else player = "x";
if (!winner.equals(" "))
JOptionPane.showMessageDialog(null,
"The winner is " + winner + "!");
}
}
}
P13.17
TicTacToeBoard.java
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
/**
The Tic Tac Toe game board
*/
public class TicTacToeBoard
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 40
/**
Constructs a TicTacToeBoard object
@param aWidth the width of the applet
@param aHeight the height of the applet
@param nCells the number of cells
@param aCellSize the size of the cell
@param aTicTacToe the TicTacToe game
*/
public TicTacToeBoard(double aWidth, double aHeight,
int nCells, double aCellSize, TicTacToe aTicTacToe)
{
width = aWidth;
height = aHeight;
cells = nCells;
cellSize = aCellSize;
t = aTicTacToe;
}
/**
Draws the Tic Tac Toe board
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
double xwidth = width - 1;
double yheight = height - 1;
double x;
double y;
TicTacToe.java
/**
The game of TicTacToe
*/
public class TicTacToe
{
/**
Construct a TicTacToe object
@param n the size of the grid
*/
public TicTacToe(int n)
{
grid = new String[n][n];
clear();
}
/**
Gets the winner
@return the winner
*/
public String getWinner()
{
// check rows
for (int i = 0; i < grid.length; i++)
{
String p = grid[i][0];
boolean same = true;
for (int j = 1; j < grid.length && same; j++)
{
if (!p.equals(grid[i][j]))
same = false;
}
if (same)
return p;
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 42
// check columns
for (int i = 0; i < grid.length; i++)
{
String p = grid[0][i];
boolean same = true;
for (int j = 1; j < grid.length && same; j++)
{
if (!p.equals(grid[j][i]))
same = false;
}
if (same)
return p;
}
// check diagonals
String p = grid[0][0];
boolean same = true;
for (int j = 1; j < grid.length && same; j++)
{
if (!p.equals(grid[j][j]))
same = false;
}
if (same)
return p;
p = grid[0][grid.length - 1];
same = true;
/**
Sets the board
@param i the ith row
@param j the jth column
@param s the status of the square
*/
public void set(int i, int j, String s)
{
if (0 <= i
&& i < grid.length
&& 0 <= j
&& j < grid[i].length
&& grid[i][j].equals(" "))
grid[i][j] = s;
}
/**
Gets the square
@param i the ith row
@param j the jth column
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 43
@return the status of the square
*/
public String get(int i, int j)
{
if (0 <= i && i < grid.length && 0 <= j && j < grid[i].length)
return grid[i][j];
else
return " ";
}
/**
Clears the board
*/
public void clear()
{
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[i].length; j++)
grid[i][j] = " ";
}
ExP13_17.java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
/**
This applet plays a game of TicTacToe
*/
public class ExP13_17 extends Applet
{
public ExP13_17()
{
current = "X";
t = new TicTacToe(NCELLS);
addMouseListener(new MouseClickListener());
}
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 44
if (current.equals("X"))
current = "O";
else
current = "X";
String winner = t.getWinner();
if (!winner.equals(" "))
{ JOptionPane.showMessageDialog(null,
"The winner is " + winner);
t.clear();
repaint();
}
}
}
P13.18
Square.java
import java.util.ArrayList;
/**
A magic square is an n x n matrix which, if filled with numbers,
the sum of the elements in each row, each column,
and the two diagonal is the same value.
*/
public class Square
{
/**
Construct a Square object
@param input the list of numbers
*/
public Square(ArrayList input)
{
size = (int) Math.sqrt(input.size());
square = new int[size][size];
{
for (int i = 0; i < size ; i++)
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 45
for (int j = 0; j < size ; j++)
{
square[i][j] = ((Integer)input.get(i * size + j)).intValue();
}
}
}
}
/**
Display the contents of the matrix
@param the ith row
@param the jth column
@return a string represenation of the matrix
*/
public String toString(int i, int j)
{
String s = " " + square[i][j];
/**
Search for a number in the matrix
@param n the number to search for
@return if the number is found, false otherwise
*/
public boolean found(int n)
{
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
if (square[i][j] == n)
return true;
}
}
return false;
}
/**
Add the numbers in the matrix
@param i the row/column to add
@return sum the sum of the row/column
*/
public int add(int i)
{
int sum = 0;
for (int j = 0; j < size; j++)
{
sum += square[i][j];
}
return sum;
}
/**
Find the sum of the diagonal
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 46
@param mainDiagonal determine if it is the main diagonal
@return sum the sum of the diagonal
*/
public int diagonalSum(boolean mainDiagonal)
{
int sum = 0;
for (int i = 0; i < size; i++)
{
int j;
if (mainDiagonal)
j = i;
else
j = size - 1 - i;
sum += square[i][j];
}
return sum;
}
/**
Determine if the matrix is a magic square
@return true if matrix is a magic square,
false otherwise
*/
public boolean isMagic()
{
for (int n = 1; n <= size * size; n++)
{
if (!found(n))
return false;
}
return true;
}
ExP13_18.java
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
This class tests the Square class.
*/
public class ExP13_18
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 47
{
public static void main(String[] args)
{
ArrayList numbers = new ArrayList();
boolean more = true;
while (more)
{
String input = JOptionPane.showInputDialog(
"Enter the next integer, or 0 when done:");
int n = Integer.parseInt(input);
if (n == 0 )
more = false;
else
numbers.add(new Integer(n));
}
System.out.println();
}
if(mySquare.isMagic())
{
JOptionPane.showMessageDialog(
null,"It's a magic square!");
}
else
{
JOptionPane.showMessageDialog(
null,"It's not a magic square!");
}
}
else
JOptionPane.showMessageDialog(
null,"Number of inputs is not a square.");
System.exit(0);
}
}
P13.19
MagicSquare.java
/**
An n x n square matrix that only works if n is odd
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 48
public class MagicSquare
{
/**
Construct a MagicSquare object
@param s the size of the matrix
*/
public MagicSquare(int s)
{
size = s;
square = new int[size][size];
init();
}
/**
Initialize the matrix array
*/
private void init()
{
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
square[i][j] = 0;
}
}
int i = size - 1;
int j = size / 2;
if (i == 0)
i = size - 1;
else
i--;
}
while (square[i][j] != 0)
{
if (i == 0)
i = size - 1;
else
i--;
}
square[i][j] = k + 1;
i = (i + 1) % size;
j = (j + 1) % size;
}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 49
}
/**
Display the contents of the matrix
@param the ith row
@param the jth column
@return a string represenation of the matrix
*/
public String toString(int i, int j)
{
String s = " " + square[i][j];
ExP13_19.java
import javax.swing.JOptionPane;
/**
This class tests the MagicSquare class
*/
public class ExP13_19
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Enter the size of the square (must be odd):");
int size = Integer.parseInt(input);
if (size % 2 == 1)
{
MagicSquare mySquare = new MagicSquare(size);
System.out.println();
}
}
else
System.out.println("Size must be odd." );
System.exit(0);
}
}
P13.20
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 50
Life.java
/**
The game of Life
*/
public class Life
{
/**
Construct a Life object
@param r the row
@param c the column
*/
public Life(int r, int c)
{
grid = new boolean[r][c];
rows = r;
columns = c;
/**
Flips the grid so that the cell gets removed
@param i the ith row
@param j the jth column
*/
public void flip(int i, int j)
{
if (0 <= i && i < rows && 0 <= j && j < columns)
grid[i][j] = !grid[i][j];
}
/**
Determine if the cell has already been added
@param i the ith row
@param j the jth column
@return true if the cell has been added, false otherwise
*/
public boolean get(int i, int j)
{
if (0 <= i && i < rows && 0 <= j && j < columns)
return grid[i][j];
else
return false;
}
/**
Counts the number of neighbors
@param i the ith row
@param j the jth column
@return neighbors the number of neighbors
*/
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 51
public int countNeighbors(int i, int j)
{
int neighbors = 0;
for (int i1 = i - 1; i1 <= i + 1; i1++)
for (int j1 = j - 1; j1 <= j + 1; j1++)
if (!(i == i1 && j == j1) && get(i1, j1)) neighbors++;
return neighbors;
}
/**
Find the next generation
*/
public void nextGeneration()
{
boolean[][] next = new boolean[rows][columns];
grid = next;
}
ExP13_20Panel.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
/**
A panel to place the game
*/
public class ExP13_20Panel extends JPanel
{
/**
Construct a ExP13_20Panel object
*/
public ExP13_20Panel()
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 52
{
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
game = new Life(ROWS, COLUMNS);
addMouseListener(new MouseClickListener());
}
/**
Draw the grid for the game
@param g the graphics context
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
double xwidth = getWidth() - 1;
double yheight = getHeight() - 1;
cellSize = Math.min(xwidth / COLUMNS, yheight / ROWS);
double x;
double y;
/**
Gets the nextGeneration
*/
public void nextGeneration()
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 53
game.nextGeneration();
repaint();
}
ExP13_20Frame.java
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
A frame for the game of Life
*/
public class ExP13_20Frame extends JFrame
{
/**
Constructs the frame
*/
public ExP13_20Frame()
{
gamePanel = new ExP13_20Panel();
getContentPane().add(gamePanel, BorderLayout.CENTER);
createControlPanel();
pack();
}
/**
Creates the control panel for the game of Life
*/
public void createControlPanel()
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 54
{
JPanel buttonPanel = new JPanel();
nextButton = new JButton("Next");
nextButton.addActionListener(new NextGenerationAction());
buttonPanel.add(nextButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
ExP13_20.java
import javax.swing.JFrame;
/**
This program tests the ExP13_20Frame
*/
public class ExP13_20
{
public static void main(String[] args)
{
JFrame appFrame = new ExP13_20Frame();
appFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
appFrame.setTitle("ExP13_20");
appFrame.show();
}
}