# Review Exercises(6)

Document Sample

```					Solutions Manual: Chapter 5             Big Java, by Cay Horstmann                         1

Review Exercises

R5.1
- if quarters > 0 then System.out.println(quarters + " quarters");

Missing parentheses (quarters > 0 ) and illegal keyword then
- if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;

Unbalanced parentheses around condition, use:
if (1 + x > Math.pow(x, Math.sqrt(2))) y = y + x;
- if (x = 1) y++; else if (x = 2) y = y + 2;

(x = 1) and (x = 2) are assignments, not comparisons, use (x == 1)
- if (x && y == 0) { x =1; y =1; }
Incompatible variable types: If x, y are integers, logical operations like && can not be
performed on them. If x, y are boolean, they can't be compared to 0. Use the following
if (x == 0 && y == 0) . . .;
-if (1 <= x <= 10)
System.out.println(x);
Invalid condition, use if(1 <= x && x <= 10)     instead.
- if (s != "nickels" || s != "pennies"
|| s != "dimes" || s != "quarters")
System.out.print("Input error !");
There is no way for the condition to evaluate true. s cannot simultaneously be nickels,
pennies, dimes or quarters. If s must be one of the choices, use the following

if (s != "nickels" && s != "pennies"
&& s != "dimes" && s != "quarters")
System.out.print("Input error !");
- if (input.equalsIgnoreCase("N") || "NO")
return;
Invalid compund condition, use the following instead:

if (input.equalsIgnoreCase("N") || input.equalsIgnoreCase("NO"))
. . .
- int x = Integer.parseInt(input);
if (x != null) y = y + x;
The integer value x can never be null. Use
if (input != null) y = y + Integer.parseInt(input);
- language = "English"
if (country.equals("USA"))
if (state.equals("PR")) language = "Spanish";
else if (country.equals("China"))
language = "Chinese";
Solutions Manual: Chapter 5             Big Java, by Cay Horstmann                         2

The indentation levels give the wrong impression: the else actually pairs with the closest
if. Use parentheses:

language = "English"
if (country.equals("USA"))
{ if (state.equals("PR")) language = "Spanish";
}
else if (country.equals("China"))
language = "Chinese";

R5.2
   An expression is a syntactical construct that is made up of constants, variables,
function calls and operators combining them. For example:

   y = x + Math.sin(Math.PI / 2)
   A condition is an expression with a Boolean value

x == 0
   A statement is a simple statement, a compound statement or a block statement.

A simple statement is an expression followed by a ;

System.out.print();
A compound statement is a statement that starts with a keyword such as if or
while, then is followed by other syntactical constructs depending on that keyword

if (x == 0)
y = z;
else
z = y;
A block statement is a group of statements enclosed in { }.

{   double root = Math.sqrt(r);
p1 = new Point2D.Double(root, b);
p2 = new Point2D.Double(-root, b);
}

R5.3
In Java if/else if /else statements are used to express a multiple alternative, in
which exactly one from a mutually exclusive set of choices is selected to be executed.
Nested if statements are used to express a selection from multiple alternatives when
there are multiple conditions for each selection.

/* value of integer choice used to select one of four possible values
for x */
if (choice == 1) x = n;
Solutions Manual: Chapter 5            Big Java, by Cay Horstmann   3

else if (choice == 2) x = n * n;
else if (choice == 3) x = n * n * n;
else x = -2;

/* value of integer choice and value of boolean available
used to select one of four possible values for x */

if (choice == 1)
{ if (x > 0)
x = n;
else
x = n * n;
}
else
{ if (x > 0)
x = n * n * n;
else
x = -2;
}

R5.4
/* Order doesn't matter */
if (choice == 1) x = n;
else if (choice == 2) x = n * n;
else if (choice == 3) x = n * n * n;
else x = 0;

/* Order matters */
if (choice < 1) x = n;
else if (choice < 2) x = n * n;
else if (choice < 3) x = n * n * n;
else x = 0;

R5.5
First               Second
Dick                Tom
Tom                 Tomato
Churchill           church
car manufacturer    carburetor
Harry               hairy
C++                 car
Tom                 Tom
Car                 Carl
bar                 car

R5.6
p       q       r       p && q || !r     !(p && (q || !r))
false   false   false   true             true
false   false   true    false            true
false   true    false   true             true
false   true    true    false            true
true    false   false   true             true
Solutions Manual: Chapter 5              Big Java, by Cay Horstmann                         4

true    false   true    false               true
true    true    false   true                false
true    true    true    true                true

R5.7
There is no level at which a tax payer ends up with less money if they have a higher
income. The income tax is progressive in that higher incomes are taxed at higher rate, but
that higher tax rate is applied only to the amount earned above the maiximum level that
can be taxed at each preceding lower rate. For example, if you earn \$21,460, the first
\$21,450 are taxed at the lower level of 15%, then the remaining \$10 are taxed at the
higher 28% rate.
If a married couple files jointly and together earn between \$35,800 and \$42,900, or
between \$86,500 and \$103,800, they will have to pay a higher tax than if they'd filed
separately if they are earning the same amount.

R5.8
If either condition has a side effect, then you cannot swap A and B. If neither condition
has a side effect, you can swap them.

R5.9
In the first block, the conditions are evaluated sequentially, so s could be incremented
twice. In the second block, the conditional statements are mutually exclusive, so, s
cannot be incremented more than once.

R5.10
Original                             De Morgan
!(x > 0 && y > 0)                    x <= 0 || y <= 0
!(x != 0 || y != 0)                  x == 0 && y == 0
!(country.equals("US") &&            !country.equals("US") ||
!state.equals("HI") &&               state.equals("HI") ||
!state.equals("AK"))                 state.equals("AK"))
x % 4 == 0 && x % 100 == 0
!(x % 4 != 0 || !(x % 100 ==         && x % 400 == 0
0 && x % 400 == 0))                  Of course, this condition can now
be simplified to x % 400 == 0

R5.11
status = "GOOD";
if (GPA >= 1.5)
if (GPA < 2.0)
status = "PROBATION";
else
status = "FAILING";
Solutions Manual: Chapter 5               Big Java, by Cay Horstmann                            5

Should be:
status = "GOOD";
if (GPA >= 1.5)
{ if (GPA < 2.0)
status = "PROBATION";
}
else
status = "FAILING";
or better:

if (GPA >= 2.0)
status = "GOOD";
else if (GPA >= 1.5)
status = "PROBATION";
else
status = "FAILING";                     }

R5.12
s == t
tests whether s and t are references to the identical String object.
s.equals(t)
tests whether s and t are strings with the same contents.

R5.13
r == s
tests whether r and s are references to the identical Rectangle object.
r.equals(s)
tests whether r and s are rectangles with the same coordinates.

R5.14
To test whether a reference is the null reference, use ==:
if (r == null)
The test r.equals(null) is supposed to return false; however, not all implementors of
the equals method test for that.

R5.15
For the lexicographic comparison, upper- and lowercase are distinguished. Also, "filler
characters" such as . - and space are used in the comparison, whereas they would be
ignored in the phonebook
Lexicographic ordering is like a dictionary alphabetic ordering, but some of the
characters have different values which results in their being sorted into a different
position. Specifically, all white space (space, horizontal tab, vertical tab, carriage return
and line feed) precede digits (0-9) which precede uppercase letters (A-Z) which precede
Solutions Manual: Chapter 5              Big Java, by Cay Horstmann                           6

lowercase letters(a-z). The sort order of punctuation and other printing characters is less
intuitive.

R5.16
if (a.getP1().equals(b.getP1()) && a.getP2().equals(b.getP2()) ||
a.getP1().equals(b.getP2()) && a.getP2().equals(b.getP1()))

R5.17
To test if an integer equals ten use:
int n ;
if(n == 10) . . .
To test if a floating point number equals ten use:
double denom = Math.abs(x);
if(Math.abs(y) < 10) denom = 10;
if((Math.abs(x - 10) / denom) <= EPSILON ) . . .

R5.18
2000000000000000 and 2000000000001001

R5.19
Marital
Income Tax
Status
S           -1    none
S           0     none
S           21000 3150.00
(21450).15 + (25000-21450).28 = 3217.00 + 994.00
S           25000 =
4211.00
(21450).15 + (51900 - 21450).28 + (60000-
S           60000
51900).31 = 3217.00 + 994.00 + 2511.00 = 6722.00
M           -1    none
M           0     none
M           35000 5250.00
(35800).15 + (57000-35800).28 = 5370.00 +
M           57000 5936.00 =
11306.00
(35800).15 + (86500 - 35800).28 + (90000-
M           90000 86500).31 = 5370.00 + 14196.00 + 1085.00 =
20651.00

R5.20
boolean xInside = r.getX() <= p.getX() && p.getX() <= r.getX() +
r.getWidth());
boolean yInside = r.getY() <= p.getY() && p.getY() <= r.getY());
if (xInside && yInside)
Solutions Manual: Chapter 5        Big Java, by Cay Horstmann           7

. . .

Programming Exercises

P5.1

{
/**
Constructs a quadratic equation and get 2 solutions
@param coefficientA coefficient a of quadratic equation
@param coefficientB coefficient b of quadratic equation
@param coefficientC coefficient c of quadratic equation
*/
double coefficientC)
{
a = coefficientA;
b = coefficientB;
c = coefficientC;
discriminant = b * b - 4 * a * c;

}

/**
Returns the first solution to the quadratic equation
@return the first solution
*/
public double getSolution1()
{
return (-b + Math.sqrt(discriminant)) / (2 * a);
}

/**
Returns the second solution to the quadratic equation
@return the second solution
*/
public double getSolution2()
{
return (-b - Math.sqrt(discriminant)) / (2 * a);
}

/**
Determines if there is a solution or not
@return true if there is a solution
*/
public boolean hasSolutions()
{
return (discriminant > 0);
}

double a;
double b;
double c;
Solutions Manual: Chapter 5            Big Java, by Cay Horstmann             8

double discriminant;
}

/**
This program tests the QuadraticEquation class.
*/

import javax.swing.JOptionPane;

{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
int a = Integer.parseInt(input);

input = JOptionPane.showInputDialog(
int b = Integer.parseInt(input);

input = JOptionPane.showInputDialog(
int c = Integer.parseInt(input);

if(myEquation.hasSolutions())
{
System.out.println(myEquation.getSolution1());
System.out.println(myEquation.getSolution2());
}
else
System.out.println("There are no solutions.");

System.exit(0);
}
}

P5.2
Card.java

/**
This class implements the full description of a deck of cards
*/
public class Card
{
/**
Constructs a card type and suit of a deck of cards
@param aType the type of the card, numbers
2-10, Jack, Queen, King, and Ace
@param aSuit the 4 suits of the card:
*/
Solutions Manual: Chapter 5        Big Java, by Cay Horstmann   9

public Card(String aType, String aSuit)
{
type = aType;
suit = aSuit;
}

/**
Get the description of the type and suit of the card
@return the description of the the card
*/
public String getDescription()
{
String output = "";

// Get the type description

if (type.equalsIgnoreCase("A"))
output = "Ace of ";
else if(type.equalsIgnoreCase("K"))
output = "King of ";
else if(type.equalsIgnoreCase("Q"))
output = "Queen of ";
else if(type.equalsIgnoreCase("J"))
output = "Jack of ";
else if(type.equals("2"))
output = "Two of ";
else if(type.equals("3"))
output = "Three of ";
else if(type.equals("4"))
output = "Four of ";
else if(type.equals("5"))
output = "Five of ";
else if(type.equals("6"))
output = "Six of ";
else if(type.equals("7"))
output = "Seven of ";
else if(type.equals("8"))
output = "Eight of ";
else if(type.equals("9"))
output = "Nine of ";
else if(type.equals("10"))
output = "Ten of ";
else
output = "Unknown type: " + type + "\n";

// Get the suit description

if (suit.equalsIgnoreCase("S"))
else if(suit.equalsIgnoreCase("H"))
output = output + "Hearts";
else if(suit.equalsIgnoreCase("D"))
output = output + "Diamonds";
else if(suit.equalsIgnoreCase("C"))
output = output + "Clubs";
else
output = output + "Unknown type: " + suit;
Solutions Manual: Chapter 5         Big Java, by Cay Horstmann       10

return output;
}

private String type;
private String suit;
}

ExP5_2.java

import javax.swing.JOptionPane;

/**
This is a test for the Card class, which outputs the full
description of a deck of cards
*/
public class ExP5_2
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Enter the card notation:");

final int MAX_NOTATION = 3;
String type = "";
String suit = "";

if(input.length() < MAX_NOTATION)
{
type = input.substring(0,1);
suit = input.substring(1,2);
}
else if(input.length() == MAX_NOTATION)
{
type = input.substring(0, 2);
suit = input.substring(2, 3);
}
else
System.out.println("Error: Wrong number of inputs!");

Card card = new Card(type, suit);
System.out.println(card.getDescription());

System.exit(0);
}
}

P5.3
LabeledPoint.java

import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

/**
A point with a label showing the point's coordinates.
*/
Solutions Manual: Chapter 5             Big Java, by Cay Horstmann       11

public class LabeledPoint
{
/**
Construct a labeled point.
@param anX the x-coordinate
@param aY the y-coordinate
*/
public LabeledPoint(double anX,double aY)
{
x = anX;
y = aY;
}

/**
Draws the point as a small circle with a coordinate label.
@param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
//draw a small circle centered around (x, y)

Ellipse2D.Double circle = new Ellipse2D.Double(

g2.draw(circle);

//draw the label

String label ="("+ x + "," + y + ")";

g2.drawString(label, (float)x, (float)y);
}

private static final double SMALL_CIRCLE_RADIUS = 2;

private double x;
private double y;
}

IntersectionApplet.java

import       java.applet.Applet;
import       java.awt.Graphics;
import       java.awt.Graphics2D;
import       java.awt.geom.Ellipse2D;
import       java.awt.geom.Line2D;
import       javax.swing.JOptionPane;

/**
An applet that computes and draws the intersection points
of a circle and a line.
*/
public class IntersectionApplet extends Applet
Solutions Manual: Chapter 5          Big Java, by Cay Horstmann        12

{
public IntersectionApplet()
{
String input
= JOptionPane.showInputDialog("x:");
x = Integer.parseInt(input);
}

/**
Method to draw the circle and compute the intersection points
*/
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;

//draw the circle

Ellipse2D.Double circle = new
g2.draw(circle);

//draw the vertical line

Line2D.Double line
= new Line2D.Double(x, 0, x, 2 * RADIUS);
g2.draw(line);

//compute the intersection points

double discriminant = RADIUS * RADIUS - (x - a) * (x - a);

if (discriminant < 0)
{
System.out.println("Error: No Intersection");
}

double root = Math.sqrt(discriminant);

double y1 = b + root;
double y2 = b - root;

//draw the intersection points

LabeledPoint p1 = new LabeledPoint(x, y1);
LabeledPoint p2 = new LabeledPoint(x, y2);

p1.draw(g2);
p2.draw(g2);
}

private static final double RADIUS = 100;
private static final double DIAMETER = RADIUS * 2;

private double x;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann     13

}

P5.4
Sort.java
/**
This class implements a list of numbers in sorted order
*/
public class Sort
{
/**
Constructs a list of numbers in sorted order
@param num1 the first number to sort
@param num2 the second number to sort
@param num3 the third number to sort
*/
public Sort(double num1, double num2, double num3)
{
x1 = num1;
x2 = num2;
x3 = num3;
}

/**
Find the numbers from smallest to largest and
put them in sorted order
*/
public void sortedOrder()
{
double smallest = x1;

if(x2 < smallest)
smallest = x2;

if(x3 < smallest)
smallest = x3;

double largest = x1;

if(x2 > largest)
largest = x2;

if(x3 > largest)
largest = x3;

double middle = x1;

if((x2 > smallest) && (x2 < largest))
middle = x2;

if((x3 > smallest) && (x3 < largest))
middle = x3;

System.out.println("The inputs in sorted order are:\n"
+ smallest + "\n" + middle + "\n" + largest);
}
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann       14

private double x1;
private double x2;
private double x3;
}

Sorter.java

/**
This class implements a list of numbers in sorted order
*/
public class Sorter
{
/**
Constructs a list of numbers in sorted order
@param num1 the first number to sort
@param num2 the second number to sort
@param num3 the third number to sort
*/
public Sorter(double num1, double num2, double num3)
{
x1 = num1;
x2 = num2;
x3 = num3;
}

/**
Gets the smallest of three numbers from an unsorted list
@return smallest the smallest of three numbers
*/
public double getSmallest()
{
double smallest = x1;

if(x2 < smallest)
smallest = x2;

if(x3 < smallest)
smallest = x3;

return smallest;
}

/**
Gets the largest of three numbers from an unsorted list
@return largest the largest of three numbers
*/
public double getLargest()
{
double largest = x1;

if(x2 > largest)
largest = x2;

if(x3 > largest)
largest = x3;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann     15

return largest;
}

/**
Gets the middle of three numbers from an unsorted list
@return middle the middle number of three numbers
*/
public double getMiddle()
{
double middle = 0;

middle = x1 + x2 + x3 - getLargest() - getSmallest();

return middle;
}

private double x1;
private double x2;
private double x3;
}

ExP5_4.java

import javax.swing.JOptionPane;

/**
This is a test class for Sort.java
*/
public class ExP5_4
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Enter the first number:");
double num1 = Double.parseDouble(input);

input = JOptionPane.showInputDialog(
"Enter the second number:");
double num2 = Double.parseDouble(input);

input = JOptionPane.showInputDialog(
"Enter the third number:");
double num3 = Double.parseDouble(input);

Sorter s = new Sorter(num1, num2, num3);

System.out.println("The inputs in sorted order are:\n"
+ s.getSmallest() + "\n"
+ s.getMiddle() + "\n"
+ s.getLargest());

System.exit(0);
}
}
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann             16

P5.5
Circle.java
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;

/**
This class implements a circle and a boolean function to
test if a user-given point is inside this circle
*/
public class Circle
{
/**
Constructs a circle and a point
@param x the x-coordinate
@param y the y-coordinate
*/
public Circle(double x, double y)
{
xLeft = x;
yTop = y;
}

/**
Draws a circle and a point
@param g2 the graphics content
*/
public void draw(Graphics2D g2)
{
// draw the circle with center (110, 120)

final double CENTERX = 110;
final double CENTERY = 120;

Ellipse2D.Double circle
g2.draw(circle);

// draw the point

Ellipse2D.Double point
= new Ellipse2D.Double(xLeft - 1, yTop - 1, 3, 3);
g2.draw(point);
}

/**
Determine if point is inside or outside the circle
@param p the point to test if it is inside the circle
@return true if the point is inside the circle
*/
public boolean isInside(Point2D.Double p)
{
double dx = xLeft - RADIUS;
double dy = yTop - RADIUS;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann   17

return ((dx * dx + dy * dy) <= (RADIUS * RADIUS));
}

private static final double RADIUS = 100;

private double xLeft;
private double yTop;
}

ExP5_5.java

import     java.applet.Applet;
import     java.awt.Graphics;
import     java.awt.Graphics2D;
import     java.awt.geom.Point2D;
import     java.awt.geom.Ellipse2D;
import     javax.swing.JOptionPane;

/**
This class tests class Circle to determine if a point
is inside a circle with center(110, 120)
*/
public class ExP5_5 extends Applet
{
public void init()
{
String input =
JOptionPane.showInputDialog("x:");
x = Integer.parseInt(input);

input =
JOptionPane.showInputDialog("y:");
y = Integer.parseInt(input);
}

public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;

Circle circle = new Circle(x, y);
circle.draw(g2);

String message;
Point2D.Double point
= new Point2D.Double(x, y);

if(circle.isInside(point))
message = "Congratulations";
else
message = "You missed.";

JOptionPane.showMessageDialog(null, message);
}

private double x;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann      18

private double y;
}

P5.6
Circle.java
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

/**
This class implements two circles and a boolean function
to test whether the two circles intersects
*/
public class Circle
{
/**
Constructs two circles and test whether the two circles intersects
*/
{
}

/**
Draws two circles
@param g2 the graphics content
*/
public void draw(Graphics2D g2)
{
if (r1 < 0 || r2 < 0)
return;

// draw the circles

Ellipse2D.Double circle1
= new Ellipse2D.Double(XCENTER1 - r1, YCENTER1 - r1,
2 * r1, 2 * r1);
g2.draw(circle1);

Ellipse2D.Double circle2
= new Ellipse2D.Double(XCENTER2 - r2, YCENTER2 - r2,
2 * r2, 2 * r2);
g2.draw(circle2);
}

/**
Tests whether or not the two circles intersect with
@return true the two circles intersects
*/
public boolean intersects(Circle other)
{
Solutions Manual: Chapter 5                Big Java, by Cay Horstmann      19

double   dx = XCENTER2 - XCENTER1;
double   dy = YCENTER2 - YCENTER1;
double   distance = Math.sqrt(dx * dx + dy * dy);
double   totalRadius = r1 + r2;

}

private   static   final   double   XCENTER1   =   100;
private   static   final   double   YCENTER1   =   200;
private   static   final   double   XCENTER2   =   200;
private   static   final   double   YCENTER2   =   100;

private double r1;
private double r2;
}

ExP5_6.java
import     java.applet.Applet;
import     java.awt.Graphics;
import     java.awt.Graphics2D;
import     java.awt.geom.Ellipse2D;
import     java.awt.geom.Point2D;
import     javax.swing.JOptionPane;

/**
This is a test for class Circle to test
whether two circles intersect
*/
public class ExP5_6 extends Applet
{
public void init()
{
String input
r1 = Integer.parseInt(input);

r2 = Integer.parseInt(input);
}

public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;

Circle circle1 = new Circle(new Point2D.Double(100, 100), r1);
circle1.draw(g2);

Circle circle2 = new Circle(new Point2D.Double(200, 200), r2);
circle2.draw(g2);

String message;

if (circle1.intersects(circle2))
message = "Circles intersect";
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann            20

else
message = "Circles don't intersect.";

JOptionPane.showMessageDialog(null, message);
}

private double r1;
private double r2;
}

import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;

/**
This class implements a circle and a method
to test whether the two circles intersects
*/
public class Circle
{
/**
Constructs two circles and test whether the two circles
intersects
@param centerPoint the center of the circle
@param r the radius of the circle
*/
public Circle(Point2D.Double centerPoint, double r)
{
center = centerPoint;
}

/**
Draws two circles
@param g2 the graphics content
*/

public void draw(Graphics2D g2)
{
Ellipse2D.Double circle
= new Ellipse2D.Double(
g2.draw(circle);
}

/**
Tests whether or not a given circle intersects with this one.
@param other the other Circle
@return true if the two circles intersects
*/
public boolean intersects(Circle other)
{
// dx is the difference between the x postions of the points
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann           21

double dx = center.getX() - other.center.getX();
// dy is the difference between the y postions of the points
double dy = center.getY() - other.center.getY();
// distance is the distance between the two centers
double distance = Math.sqrt(dx * dx + dy * dy);

}

private Point2D.Double center;
}

P5.7
InputChecker.java
/**
This class checks if the user wants to continue
*/
public class InputChecker
{
/**
Constructs an input checker to determine if user
wants to continue
@param anInput the input of the user
*/
public InputChecker(String anInput)
{
input = anInput;
result = 0;
}

/**
Checks the user's input
@result the result of checking the input
*/
public int checkInput()
{
if (input.equalsIgnoreCase("Y") ||
input.equalsIgnoreCase("Yes") ||
input.equalsIgnoreCase("Sure") ||
input.equalsIgnoreCase("Why not?") ||
input.equalsIgnoreCase("OK"))
result = 1;

else if (input.equalsIgnoreCase("N") ||
input.equalsIgnoreCase("No"))
result = -1;

return result;
}

/**
Test if the user wants to continue
@return true the user wants to continue
*/
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann   22

public boolean isYes()
{
return (checkInput() > 0);
}

/**
Test if the user does not want to continue
@return true the user does not want to continue
*/
public boolean isNo()
{
return (checkInput() < 0);
}

private String input;
private int result;
}

ExP5_7.java

import javax.swing.JOptionPane;

/**
This tests the InputChecker class
*/
public class ExP5_7
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Do you want to continue?");

InputChecker c = new InputChecker(input);

if(c.isYes())
System.out.println("OK");
else if (c.isNo())
System.out.println("Terminating");
else

System.exit(0);
}
}

P5.8

/**
This class finds the numeric representation of a letter grade
*/
{
/**
Solutions Manual: Chapter 5             Big Java, by Cay Horstmann   23

@param mod the modifier of the letter, either a + or a -
*/
{
modifier = mod;
}

/**
*/
{

if (letter.equalsIgnoreCase("a"))
else if (letter.equalsIgnoreCase("b"))
else if (letter.equalsIgnoreCase("c"))
else if (letter.equalsIgnoreCase("d"))
else if (letter.equalsIgnoreCase("f"))
{
modifier = 0;
}
else
{
}

// There is no grade higher than an A

}

private String letter;
private double modifier;
}

ExP5_8.java

import javax.swing.JOptionPane;

/**
Solutions Manual: Chapter 5             Big Java, by Cay Horstmann       24

This class tests Grade class to find a numeric representation of
a letter grade given by user
*/
public class ExP5_8
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(

String letter = input.substring(0,1);
String mod = "";

if (input.length() > 1)
mod = input.substring(1,2);

double modifier = 0;

if (mod.equals("-"))
modifier = -0.3;
else if (mod.equals("+"))
modifier = 0.3;

else

System.exit(0);
}
}

P5.9

/**
This class finds the letter representation of a numeric grade
*/
{
/**
*/
{
}

/**
Solutions Manual: Chapter 5         Big Java, by Cay Horstmann           25

*/
{
String letter = "";
String mod= "";

if (input >= 0 && input <= 4.5)
{
if (input >= 3.5 )
letter = "A";
else if (input >= 2.5 )
letter = "B";
else if (input >= 1.5 )
letter = "C";
else if (input >= 0.5 )
letter = "D";
else
letter = "F";
}
else
letter = "That is not valid";

double remainder = input - (int)input;

if ((0.5 <= remainder) && (remainder < 0.85))
mod = "-";
else if ((0.15 <= remainder) && (remainder < 0.5))
mod = "+";

return letter + mod;
}

private double input;
}

ExP5_9.java

import javax.swing.JOptionPane;

/**
This class tests the class Grade to find a letter representation
*/
public class ExP5_9
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(

System.exit(0);
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann          26

}
}

P5.10
Comparer.java

/**
This class compares four strings and prints the lexicographically
smallest and largest one
*/
public class Comparer
{
/**
Constructs four strings to compare
*/
public Comparer()
{
smallest = null;
largest = "";
}

/**
Add a string to the list and compare
@param s the string to compare
*/
{
if(smallest == null || s.compareTo(smallest) < 0)
smallest = s;
if(s.compareTo(largest) > 0)
largest = s;
}

/**
The smallest of the four strings
@return smallest the smallest of the strings
*/
public String smallest()
{
return smallest;
}

/**
The largest of the four strings
@return largest the largest of the strings
*/
public String largest()
{
return largest;
}

private String smallest;
private String largest;
}

ExP5_10.java
Solutions Manual: Chapter 5         Big Java, by Cay Horstmann         27

import javax.swing.JOptionPane;

/**
This is a test class for Compare to determine the lexicographical
smallest
and largest string.
*/
public class ExP5_10
{
public static void main(String[] args)
{
String string1 = JOptionPane.showInputDialog(
"Enter the first string:");

String string2 = JOptionPane.showInputDialog(
"Enter the second string:");

String string3 = JOptionPane.showInputDialog(
"Enter the third string:");

String string4 = JOptionPane.showInputDialog(
"Enter the fourth string:");

Comparer c = new Comparer();

System.out.println("The lexicographic minimum is " +
c.smallest());
System.out.println("The lexicographic maximum is " + c.largest());

System.exit(0);
}
}

P5.11
TaxReturn.java

/**
Class TaxReturn is used to determine the tax amount for a person
*/
public class TaxReturn
{
/**
Constructs an object TaxReturn
@param anIncome of a person
@param aStatus of a person...i.e. single or married
*/

public TaxReturn(double anIncome, String aStatus)
{
income = anIncome;
Solutions Manual: Chapter 5          Big Java, by Cay Horstmann   28

status = aStatus;
}

/**
Method used to determine the status of a person
and calculate the tax
@return the tax amount
*/
public double getTax()
{
double tax = 0;

final double RATE1 = 0.15;
final double RATE2 = 0.28;
final double RATE3 = 0.31;

final double SINGLE_CUTOFF1 = 21450;
final double SINGLE_CUTOFF2 = 51900;

final double SINGLE_BASE2 = 3217.50;
final double SINGLE_BASE3 = 11743.50;

final double MARRIED_CUTOFF1 = 35800;
final double MARRIED_CUTOFF2 = 86500;

final double MARRIED_BASE2 = 5370;
final double MARRIED_BASE3 = 19566;

double cutoff1;
double cutoff2;

if (status.equalsIgnoreCase("S"))
{
cutoff1 = SINGLE_CUTOFF1;
cutoff2 = SINGLE_CUTOFF2;
}
else /* status is M */
{
cutoff1 = MARRIED_CUTOFF1;
cutoff2 = MARRIED_CUTOFF2;
}

if (income < cutoff1)
tax = RATE1 * income;
else if (income < cutoff2)
tax = RATE1 * cutoff1 + (income - cutoff1) * RATE2;
else
tax = RATE1 * cutoff1 + RATE2 * (cutoff2 - cutoff1)
+ RATE3 * (income - cutoff2);

return tax;
}

private double income;
private String status;
}
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann       29

ExP5_11.java

import javax.swing.JOptionPane;

/**
This is test class for TaxReturn class
*/

public class ExP5_11
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
double income = Double.parseDouble(input);

String status = JOptionPane.showInputDialog(
"Please enter S for single, M for married:");

TaxReturn aTaxReturn = new TaxReturn(income, status);

System.out.println("The tax is " + aTaxReturn.getTax());

System.exit(0);
}
}

P5.12
Year.java

/**
This class determines if a year is a leap year or not
*/
public class Year
{
/**
Creates a Year object to test whether a particular year is a leap
year
@param aYear is the year to be tested
*/
public Year(int aYear)
{
year = aYear;
}

/**
Method to determine if a year is a leap year
@return boolean true year is a leap year
*/
public boolean isLeapYear()
{
double a = year % 4;
double b = year % 100;
double c = year % 400;
double gregorian = 1582;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann             30

return (a == 0 && (year < gregorian || b != 0 || c == 0));
}

private int year;
}

ExP5_12.java

import javax.swing.JOptionPane;

/**
This is a test class driver for Year class
*/
public class ExP5_12
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
int year = Integer.parseInt(input);

Year aYear = new Year(year);

if(aYear.isLeapYear())
System.out.println("The year " + year + " is a leap year");

else
System.out.println("The year " + year + " is a not leap year");

System.exit(0);
}
}

5.13
Month.java

/**
This class determines the number of days in a month
*/
public class Month
{
/**
Creates a Month object to determine the number of days in a month
@param aMonth is the month in numeric format to determine the
number of days
*/
public Month(int aMonth)
{
month = aMonth;
}

/**
Method to get the number of days in the month
@return the days in the tested month
*/
Solutions Manual: Chapter 5         Big Java, by Cay Horstmann         31

public int getDays()
{
int days;

if (month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
else if (month == 2)
days = 28;
else if (1 <= month && month <= 12)
days = 31;
else
days = -1;

return days;
}

private int month;
}

ExP5_13.java

import javax.swing.JOptionPane;

/**
This is a test driver class for Month class
*/
public class ExP5_13
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Please enter the number of a month:");
int month = Integer.parseInt(input);

Month m = new Month(month);

int days = m.getDays();

if (days < 0)
else
System.out.println(days + " days");

System.exit(0);
}
}

P5.14
Comparator.java

/**
This class is used to test whether two floating numbers are the same
*/
public class Comparator
{
/**
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann        32

Creates a FloatingNumbers object to determine if two inputs are
approximately the same
@param d the number of significant digits in the comparison
*/
public Comparator(int d)
{
digits = d;
}

/**
Method to test the equality of the two inputs
@param x1 the first number
@param x2 the second number
@return true the two numbers are the same
*/
public boolean isSameNumber(double x1, double x2)
{
double absoluteValue = Math.abs(x1 - x2);
return (absoluteValue < Math.pow(0.1, digits));
}

private int digits;
}

ExP5_14.java

import javax.swing.JOptionPane;

/**
This is a test class for FloatingNumbers.
*/
public class ExP5_14
{
public static void main(String[] args)
{
Comparator c = new Comparator(2);

String input = JOptionPane.showInputDialog(
"Enter the first floating-point number:");
double f1 = Double.parseDouble(input);

input = JOptionPane.showInputDialog(
"Enter the second floating-point number:");
double f2 = Double.parseDouble(input);

System.out.println( "They are the same up to two decimal
places.");
else
System.out.println( "They are different.");

System.exit(0);
}
}

P5.15
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann   33

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)
{
if (initialBalance >= 0)
balance = initialBalance;
}

/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
if (amount >= 0)
{
double newBalance = balance + amount;
balance = newBalance;
}
}

/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
if (amount <= balance)
{
double newBalance = balance - amount;
balance = newBalance;
}
}

/**
Gets the current balance of the bank account.
@return the current balance
*/
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann         34

public double getBalance()
{
return balance;
}

private double balance;
}

ExP5_15.java

import javax.swing.JOptionPane;

/**
This is a test driver class for BankAccount class
*/
public class ExP5_15
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(
"Enter deposit:");
double dep = Double.parseDouble(input);

input = JOptionPane.showInputDialog(
"Enter withdrawal:");
double wit = Double.parseDouble(input);

BankAccount account = new BankAccount();
account.deposit(dep);
account.withdraw(wit);

System.out.println("Balance is \$" + account.getBalance());

System.exit(0);
}
}

P5.16
PayCheck.java

/**
This class is used to calculate an employee's pay
*/
public class PayCheck
{
/**
Creats a PayCheck object to determine employee's pay
@param aName is the name of employee
@param aWage is the employee's wage
@param anHour is the amount of hours worked
*/
public PayCheck(String aName, double aWage, double anHour)
{
name = aName;
wage = aWage;
hours = anHour;
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann               35

}

/**
Method calculates an employee's pay
@return pay is total pay for an employee
*/
public double getWages()
{
double pay = 0.0;

final int OT_THRESHOLD = 40;
final double OT_RATE = 1.5;

if (hours > OT_THRESHOLD)
{
double regular_hours = OT_THRESHOLD;
double overtime_hours = hours - OT_THRESHOLD;

pay = regular_hours * wage + OT_RATE * overtime_hours * wage;
}
else
pay = hours * wage;

return pay;
}

private String name;
private double wage;
private double hours;
}

ExP5_16.java

import javax.swing.JOptionPane;

/**
This is a test driver class for PayCheck class
*/
public class ExP5_16
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog(
"Enter an Employee's name:");

String input = JOptionPane.showInputDialog(
"Enter an hourly wage for " + name + ": ");
double wage = Double.parseDouble(input);

input = JOptionPane.showInputDialog(
"How many hours did " + name + " work this past week? : ");
double hours = Double.parseDouble(input);

PayCheck aPayCheck = new PayCheck(name, wage, hours);
Solutions Manual: Chapter 5            Big Java, by Cay Horstmann      36

System.out.println(name + " gets \$" + aPayCheck.getWages() + "
this pay period.");

System.exit(0);

}
}

P5.17
UnitConverter.java

/**
This class implements a unit converter for
converting from one unit to another
*/
public class UnitConverter
{
/**
Constructs a unit converter to converter
from one unit to another
@param unit the unit to convert either from or to
*/
public UnitConverter(String unit)
{
final double FLUID_OUNCE_TO_LITER = 29586;
final double GALLON_TO_LITER = 3.758;
final double OUNCE_TO_GRAM = 28.3495;
final double POUND_TO_GRAM = 453.6;
final double INCH_TO_METER = 0.0254;
final double FOOT_TO_METER = 0.305;
final double MILE_TO_METER = 1609;

if (unit.equals("fl.oz"))
factor = FLUID_OUNCE_TO_LITER;

else if (unit.equals("ml"))
factor = 0.001;

else if (unit.equals("l"))
factor = 1;

else if (unit.equals("oz"))
factor = OUNCE_TO_GRAM;

else if (unit.equals("lb"))
factor = POUND_TO_GRAM;

else if (unit.equals("mg"))
factor = 0.001;

else if (unit.equals("g"))
factor = 1;

else if (unit.equals("kg"))
factor = 1000;
Solutions Manual: Chapter 5              Big Java, by Cay Horstmann   37

else if (unit.equals("in"))
factor = INCH_TO_METER;

else if (unit.equals("ft"))
factor = FOOT_TO_METER;

else if (unit.equals("mi"))
factor = MILE_TO_METER;

else if (unit.equals("mm"))
factor = 0.001;

else if (unit.equals("cm"))
factor = 0.01;

else if (unit.equals("m"))
factor = 1;

else if (unit.equals("km"))
factor = 1000;
else
factor = -1;

}

/**
Converts a measurement to metric
@param measurement the measurement to convert
to metric
@return metric measurement
*/
public double toMetric(double measurement)
{
return measurement * factor;
}

/**
Converts a measurement from metric
@param measurement the measurement to convert
from metric
@return measurement that is converted
*/
public double fromMetric(double measurement)
{
return measurement / factor;
}

private String type;
private double factor;
}

ExP5_17.java

import javax.swing.JOptionPane;

/**
Solutions Manual: Chapter 5           Big Java, by Cay Horstmann         38

This is a test driver for the UnitConverter class
*/
public class ExP5_17
{
public static void main(String[] args)
{
String fromUnit = JOptionPane.showInputDialog(
"Convert from:");

String toUnit = JOptionPane.showInputDialog(
"Convert to:");

UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);

String input = JOptionPane.showInputDialog(
"Value:");
double value = Double.parseDouble(input);

double metric = from.toMetric(value);
double converted = to.fromMetric(metric);

if(converted < 0)
else
System.out.println(value + " " + fromUnit +
" = " + converted + " " + toUnit);

System.exit(0);
}
}

P5.18
CombinationLock.java

/**
This class implements a combination lock
*/
public class CombinationLock
{
/**
Constructs a lock with a given combination.
@param aCombination the combination; a string
with three uppercase letters A . . . Z
*/
public CombinationLock(String aCombination)
{
combination = aCombination;
newPosition = "";
open = false;
}

/**
Set the dial to a position.
@param aPosition a string consisting of a single uppercase
letter A . . . Z
Solutions Manual: Chapter 5            Big Java, by Cay Horstmann            39

*/
void setPosition(String aPosition)
{
position = aPosition;
newPosition += position;

if(newPosition.length() > 3)
{
int startIndex = newPosition.length() - 3;
int stopIndex = newPosition.length();
newPosition = newPosition.substring(startIndex, stopIndex);
}
}

/**
Try unlocking the lock.
*/
void unlock()
{
if(newPosition.equals(combination))
open = true;
}

/**
Check whether the lock is unlocked.
@return true if the lock is currently open.
*/
boolean isOpen()
{
return open;
}

/**
Close the lock.
*/
void lock()
{
newPosition = "";
position = "";
open = false;
}

private    boolean open;
private    String newPosition;
private    String combination;
private    String position;
}

ExP5_18.java

import javax.swing.JOptionPane;

/**
This is a test driver class for CombinationLock class
*/
public class ExP5_18
Solutions Manual: Chapter 5          Big Java, by Cay Horstmann   40

{
public static void main(String[] args)
{
String combination = JOptionPane.showInputDialog(
"Enter a combination:");
combination = combination.toUpperCase();

CombinationLock aCombinationLock = new
CombinationLock(combination);

String position1 = JOptionPane.showInputDialog(
"Enter the first position:");
position1 = position1.toUpperCase();
String position2 = JOptionPane.showInputDialog(
"Enter the second position:");
position2 = position2.toUpperCase();
String position3 = JOptionPane.showInputDialog(
"Enter the third position:");
position3 = position3.toUpperCase();

aCombinationLock.setPosition(position1);
aCombinationLock.setPosition(position2);
aCombinationLock.setPosition(position3);

aCombinationLock.unlock();

if(aCombinationLock.isOpen())
System.out.println("The lock is opened");
else
System.out.println("The lock is not opened");

aCombinationLock.lock();

System.exit(0);
}
}

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 0 posted: 11/15/2012 language: Latin pages: 40
pptfiles