Вы находитесь на странице: 1из 54

Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 1

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;

public class ExR13_2


{
public static void main(String[] args)
{
ArrayList a = new ArrayList();
a.add("a");
a.add("b");
String c = (String)a.get(2);
}
}
When you run this program, you get an array index out of bounds exception.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2,


Size: 2
at java.util.ArrayList....
at ...
at ExR13_2.main(ExR13_2.java:10)
The line number (:10 in the example) helps you locate the error.

R13.3
import java.util.ArrayList;

public class ExR13_3


{
public static void main(String[] args)
{
ArrayList coins = new ArrayList();
coins.add(new Coin(0.10, "dime"));
coins.add(new Coin(0.25, "quarter"));
coins.add(new Coin(0.01, "penny"));
coins.add(new Coin(0.05, "nickel"));

Coin max = (Coin)coins.get(0);


Coin min = (Coin)coins.get(0);
for (int i = 1; i < coins.size(); i++)
{
Coin c = (Coin)coins.get(i);
if (c.getValue() max.getValue())
max = c;

if (c.getValue()
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 2
R13.4
import java.util.ArrayList;
import java.util.StringTokenizer;

public class ExR13_4


{
public static void main(String[] args)
{
ArrayList stringList = new ArrayList();

String input = "The department store has many " +


"items you can choose from";

StringTokenizer t = new StringTokenizer(input);

while (t.hasMoreTokens())
stringList.add(t.nextToken());

for (int i = stringList.size() - 1; i = 0; i--)


System.out.println(stringList.get(i));
}
}

R13.5
 1 2 3 4 5 6 7 8 9 10

for (int i = 0; i < 10 ; i++ )


a[i] = i + 1;
 0 2 4 6 8 10 12 14 16 18 20

for (int i = 0; i < 10 ; i++ )


a[i] = 2 * i;
 1 4 9 16 25 36 49 64 81 100

for (int i = 0; i < 10 ; i++ )


a[i] = (i + 1) * (i + 1);
 0000000000

for (int i = 0; i < 10 ; i++ )


a[i] = 0;
 1 4 9 16 9 7 4 9 11

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);

int[] a = new int[10];


Random generator = new Random();
int i = 0;
while (i
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 3

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];

for (int i = 0; i < 10; i++)


data[i] = (i + 1) * (i + 1);
}
}
The contents of the array beyond those that were filled are all zeros: 1, 4, 9, ..., 100, 0, 0, 0, ..., 0

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();
}

private ArrayList accountList;


}

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);
}

private double balance;


}

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;
}

public boolean equals(Object otherObject)


{
Coin other = (Coin)otherObject;
return name.equals(other.name)
&& value == other.value;
}

/**
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[";

for (int i = 0; i < coins.size(); i++)


{
output += coins.get(i);
if (i != coins.size() - 1)
output += ",";
}

return output + "]";

private ArrayList coins;


}

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;
}

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.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

for (int i = 0; i < coins.size(); i++)


{
Coin c = (Coin)coins.get(i);
output += c.getName();
if (i != coins.size() - 1)
output += ",";
}

return output + "]";

private ArrayList coins;


}

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;
}

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.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();
}

private ArrayList coins;


}

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"));

Purse b = new Purse();


b.add(new Coin(0.10, "Dime"));
b.add(new Coin(0.05, "Nickel"));

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;
}

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.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();
}

private ArrayList coins;


}

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"));

Purse b = new Purse();


b.add(new Coin(0.25, "Quarter"));
b.add(new Coin(0.10, "Dime"));

System.out.println(a.equals(b));

Purse c = new Purse();


c.add(new Coin(0.05, "Nickel"));
c.add(new Coin(0.10, "Dime"));

Purse d = new Purse();


d.add(new Coin(0.05, "Nickel"));
d.add(new Coin(0.25, "Quarter"));

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;
}

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.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;

for (int i = 0; i < coins.size(); i++)


{
Coin c = (Coin)coins.get(i);
if (count(c) != p.count(c))
return false;
}

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;
}

private ArrayList coins;


private ArrayList equalCoins;
}

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"));

Purse b = new Purse();


b.add(new Coin(0.05, "Nickel"));
b.add(new Coin(0.10, "Dime"));
b.add(new Coin(0.10, "Dime"));
b.add(new Coin(0.25, "Quarter"));

System.out.println(a.equals(b));

Purse c = new Purse();


c.add(new Coin(0.25, "Quarter"));
c.add(new Coin(0.01, "Penny"));
c.add(new Coin(0.05, "Nickel"));
c.add(new Coin(0.10, "Dime"));

Purse d = new Purse();


d.add(new Coin(0.05, "Nickel"));
d.add(new Coin(0.10, "Dime"));
d.add(new Coin(0.10, "Dime"));
d.add(new Coin(0.25, "Quarter"));

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);
}
}

private ArrayList points;


private final int RADIUS = 5;
}

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;

Cloud c = new Cloud();

Random generator = new Random();


double x = 0;
double y = 0;

for (int i = 0; i < 20; i++)


{
x = 10 * generator.nextDouble();
y = 10 * generator.nextDouble();
c.add(new Point2D.Double(x, y));
}

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.
*/

public class Polygon


{
/**
Constructs a polygon
*/
public Polygon()
{
points = new ArrayList();
}

/**
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));
}
}

private ArrayList points;


}

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;

Polygon square = new Polygon();

square.add(new Point2D.Double(100, 100));


square.add(new Point2D.Double(100, 150));
square.add(new Point2D.Double(150, 150));
square.add(new Point2D.Double(150, 100));

square.draw(g2);

Polygon pentagon = new Polygon();

pentagon.add(new Point2D.Double(150, 150));


pentagon.add(new Point2D.Double(175, 200));
pentagon.add(new Point2D.Double(225, 200));
pentagon.add(new Point2D.Double(250, 150));
pentagon.add(new Point2D.Double(200, 100));

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.
*/

public class Polygon


{
/**
Constructs a polygon
*/
public Polygon()
{
points = new ArrayList();
}

/**
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;

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());
a = a + from.getX() * to.getY() - from.getY() * to.getX();
}
return 0.5 * Math.abs(a);
}

private ArrayList points;


}

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)
{

Polygon square = new Polygon();

square.add(new Point2D.Double(100, 100));


square.add(new Point2D.Double(100, 150));
square.add(new Point2D.Double(150, 150));
square.add(new Point2D.Double(150, 100));

Polygon pentagon = new Polygon();


Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 26
pentagon.add(new Point2D.Double(150, 150));
pentagon.add(new Point2D.Double(175, 200));
pentagon.add(new Point2D.Double(225, 200));
pentagon.add(new Point2D.Double(250, 150));
pentagon.add(new Point2D.Double(200, 100));

double squareCircumference = square.perimeter();


System.out.println("Square perimeter = " + squareCircumference);

double squareArea = square.area();


System.out.println("Square area = " + squareArea);

double pentagonCircumference = pentagon.perimeter();


System.out.println("Pentagon perimeter = " + pentagonCircumference);

double pentagonArea = pentagon.area();


System.out.println("Pentagon area = " + pentagonArea);
}
}

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;
}

private double[] data;


private int dataSize;
}

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);

double sum = data.alternatingSum();


System.out.println("Alternating Sum = " + sum);
}
}

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];

for (int i = 0; i < n; i++)


{ int pos = generator.nextInt(pSize);
r[i] = p[pos];
p[pos] = p[pSize - 1];
pSize--;
}
return r;
}

private Random generator;


}

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;

PermutationGenerator p = new PermutationGenerator();

for (int i = 0; i < MAX_PERM; i++)


{
print(p.nextPermutation(MAX_NUM));
}
}

/**
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 xwidth = width - 1;


double yheight = height - 1;

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;
}
}

private double width;


private double height;
private ArrayList data;
}

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 xwidth = width - 1;


double yheight = height - 1;

double xleft = 0;

for (i = 0; i < data.size(); i++)


{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();
double xright = xwidth * (i + 1) / data.size();
double barWidth = xwidth / data.size();
double barHeight = yheight * x / max;

Rectangle2D.Double bar =
new Rectangle2D.Double(xleft, yheight - barHeight,
barWidth, barHeight);
g2.draw(bar);

xleft = xright;
}
}

private double width;


private double height;
private ArrayList data;
}

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 xwidth = width - 1;


double yheight = height - 1;

double xleft = 0;
double ybase = yheight * max / (max - min);

for (i = 0; i < data.size(); i++)


{
Double wrapper = (Double)data.get(i);
double x = wrapper.doubleValue();

double xright = xwidth * (i + 1) / data.size();


double barWidth = xwidth / data.size();
double y = yheight * x / (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;
}
}

private double width;


private double height;
private ArrayList data;
}

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 xwidth = width - 1;


double yheight = height - 1;
double radius = Math.min(xwidth, yheight) / 2;

g2.draw(new Ellipse2D.Double(0, 0, 2 * radius, 2 * radius));

Point2D.Double center = new Point2D.Double(radius, radius);

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));
}
}

private double width;


private double height;
private ArrayList data;
}

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];

// fill with spaces


for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";
}

/**
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;

for (int j = 1; j < board.length && same; j++)


{
if (!p.equals(board[j][board.length - 1 - j]))
same = false;
}
if (same)
return p;
return " ";
}

private String[][] board;


Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 39
private static final int ROWS = 3;
private static final int COLUMNS = 3;
}

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";

String winner = game.getWinner();

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;

// draw vertical lines


for (int i = 1; i < cells; i++)
{
x = i * cellSize;
Point2D.Double p = new Point2D.Double(x, 0);
Point2D.Double q = new Point2D.Double(x, cells * cellSize);
g2.draw(new Line2D.Double(p, q));
}

// draw horizontal lines


for (int i = 1; i < cells; i++)
{
y = i * cellSize;
Point2D.Double p = new Point2D.Double(0, y);
Point2D.Double q = new Point2D.Double(cells * cellSize, y);
g2.draw(new Line2D.Double(p, q));
}

for (int i = 0; i < cells; i++)


for (int j = 0; j < cells; j++)
{
x = i * cellSize;
y = j * cellSize;
if (t.get(i, j).equals("X"))
{
Point2D.Double p = new Point2D.Double(x, y);
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 41
Point2D.Double q = new Point2D.Double(x + cellSize, y +
cellSize);
g2.draw(new Line2D.Double(p, q));
p = new Point2D.Double(x, y + cellSize);
q = new Point2D.Double(x + cellSize, y);
g2.draw(new Line2D.Double(p, q));
}
if (t.get(i, j).equals("O"))
{
g2.draw(new Ellipse2D.Double(x, y, cellSize, cellSize));
}
}
}

private double width;


private double height;
private int cells;
private double cellSize;
private TicTacToe t;
}

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;

for (int j = 1; j < grid.length && same; j++)


{
if (!p.equals(grid[j][grid.length - 1 - j]))
same = false;
}
if (same)
return p;
return " ";
}

/**
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] = " ";
}

private String[][] grid;


}

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());
}

public void paint(Graphics g)


{
Graphics2D g2 = (Graphics2D)g;

double xwidth = getWidth() - 1;


double yheight = getHeight() - 1;
cellSize = Math.min(xwidth, yheight) / NCELLS;

TicTacToeBoard board = new TicTacToeBoard(getWidth(),


getHeight(), NCELLS, cellSize, t);
board.draw(g2);

}
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 44

private class MouseClickListener extends MouseAdapter


{
public void mousePressed(MouseEvent event)
{
int mouseX = (int)(event.getX() / cellSize);
int mouseY = (int)(event.getY() / cellSize);

if (!t.get(mouseX, mouseY).equals(" "))


return;
t.set(mouseX, mouseY, current);
repaint();

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();
}
}
}

private String current;


private TicTacToe t;
private double cellSize;
private final int NCELLS = 3;
}

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];

return s.substring(s.length() - 3, s.length());


}

/**
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;
}

int sum = diagonalSum(true);


if (sum != diagonalSum(false))
return false;

for (int i = 0; i < size; i++)


{
if (sum != add(i))
return false;
}

return true;
}

private int[][] square;


private int size;
}

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));
}

int size = (int) Math.sqrt(numbers.size());


if (size * size == numbers.size())
{
Square mySquare = new Square(numbers);
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
System.out.print(mySquare.toString(i , j));
}

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;

for (int k = 0; k < size * size ; k++)


{
/* [i][j] has been written already */
if (square[i][j] != 0)
{
if (j == 0 )
j = size - 1;
else
j--;

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];

return s.substring(s.length() - 3, s.length());


}

private int[][] square;


private int size;
}

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);

for (int i = 0; i < size ; i++)


{
for (int j = 0; j < size ; j++)
{
System.out.print(mySquare.toString(i , j));
}

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;

/* initialize all to false */


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
grid[i][j] = false;
}
}

/**
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];

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < columns; j++)
{
int neighbors = countNeighbors(i, j);
if (get(i, j))
next[i][j] = neighbors == 2 || neighbors == 3;
else
next[i][j] = neighbors == 3;
}
}

grid = next;
}

private int rows;


private int columns;
private boolean[][] grid;
}

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;

// draw vertical lines


for (int i = 1; i < COLUMNS; i++)
{
x = i * cellSize;
Point2D.Double p = new Point2D.Double(x, 0);
Point2D.Double q = new Point2D.Double(x, ROWS * cellSize);
g2.draw(new Line2D.Double(p, q));
}

// draw horizontal lines


for (int i = 1; i < ROWS; i++)
{
y = i * cellSize;
Point2D.Double p = new Point2D.Double(0, y);
Point2D.Double q = new Point2D.Double(COLUMNS * cellSize, y);
g2.draw(new Line2D.Double(p, q));
}

for (int i = 0; i < ROWS; i++)


for (int j = 0; j < COLUMNS; j++)
{
y = i * cellSize;
x = j * cellSize;
if (game.get(i, j))
{
g2.fill(new Ellipse2D.Double(x, y, cellSize, cellSize));
}
}
}

/**
Gets the nextGeneration
*/
public void nextGeneration()
{
Solutions Manual: Chapter 13 Big Java , by Cay Horstmann 53
game.nextGeneration();
repaint();
}

private Life game;


private double cellSize;

private final int ROWS = 50;


private final int COLUMNS = 60;
private static final int PANEL_WIDTH = 300;
private static final int PANEL_HEIGHT = 300;

private class MouseClickListener extends MouseAdapter


{
public void mousePressed(MouseEvent event)
{
int mouseX = (int)(event.getX() / cellSize);
int mouseY = (int)(event.getY() / cellSize);
game.flip(mouseY, mouseX);
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");

class NextGenerationAction implements ActionListener


{
public void actionPerformed(ActionEvent event)
{
gamePanel.nextGeneration();
}
}

nextButton.addActionListener(new NextGenerationAction());

buttonPanel.add(nextButton);

getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}

private JButton nextButton;


private ExP13_20Panel gamePanel;
}

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();
}
}

Вам также может понравиться