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.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() <min.getValue())

min = c;

}

System.out.println(max.getValue() + " " + max.getName());

System.out.println(min.getValue() + " " + min.getName());

}

}

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

  • 0 0 0 0 0 0 0 0 0 0

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

All elements of an array are of the same type / true
Array subscripts must be integers / true
Arrays cannot contain strings as elements / false, for example main(String[] 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 of rows as columns / false (square matrices, however do)
Two parallel arrays can be replaced by a two-dimensional array / false (the array elements might be of different type)
Elements of different columns in a matrix can have different types / false
Elements in an array list can have different types / true

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)

{

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;

}

/**

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

{

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

{

/**

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

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

*/

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

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

Cloud.java

import java.awt.geom.Point2D;

import java.awt.geom.Ellipse2D;

import java.awt.Graphics2D;

import java.util.ArrayList;

/**

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)

{

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

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)

{

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;

}

/**

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

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

}

}

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.

*/

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

{

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

c.add(2.1);

c.add(2.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;

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