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

Total Page:16

File Type:pdf, Size:1020Kb

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

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

Review Exercises

R7.1 class VendingMachine to display available products class Product to represent the each product in the machine class Coin to represent coin values such as quarters, nickels, etc.

R7.3 class Customer handles the information of a customer object, its shipping and billing addresses, and what product this customer ordered. class Invoice generates the products that the customer ordered, create an invoice and calculate the amount due. class Product represents the name of the products and the amount it costs class Address represents the shipping and billing addresses of each customer

R7.5

R7.7 The Integer class depends on the String class.

R7.9 int countTokens() - Accessor boolean hasMoreElements() - Accessor Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 2

boolean hasMoreTokens() - Accessor

Object nextElement() - Mutator

String nextToken() - Mutator

String nextToken(String delim) - Mutator

R7.11 Of the three class, Rectangle, String, and Random, only class String is immutable

R7.13 public void print() The side effect is using System.out to print on the console public void print(PrintStream stream) The side effect is modifying the stream parameter public String toString() There is no side effect

R7.15 /** computes the square root of a number @param x the number @return the square root (Precondition: x >= 0) */ public static double sqrt(double x)

/** converts an integer to its Roman numeral form @param n the integer to be converted @return the Roman numeric equivalent (Precondition: n >= 0) */ public static String romanNumeral(int n)

/** computes the slope of a line. The line should not be vertical @param a the Line object @return the slope (Precondition: a is not vertical) */ public static double slope(Line2D.Double a)

/** converts a day into its English name form @param day the day (0 = Monday, 1 = Tuesday, . . . , 6 = Sunday) Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 3

@return the English name form of the day (Precondition: day <= 7 && day >= 0) */ public static String weekday(int day)

R7.17 Integer.parseInt(String s): The characters in the string must all be decimal digits

StringTokenizer.nextToken(): hasMoreTokens() must be true

Random.nextInt(int n): n > 0

String.substring(int m, int n): m > 0 && n < String.length() && m <= n

R7.19 /** Add a coin to the purse @param aCoin a coin representing quarters, nickels, dimes, or pennies (Precondition: aCoin.getValue > 0) (Postcondition: getTotal() > 0) */ public void addCoin(Coin aCoin)

R7.21 public static void swap(Point2D.Double p) { p.setLocation(p.getY(), p.getX()); } public static void main(String[] args) { double x = 3; double y = 4; Point2D.Double p = new Point2D.Double(x, y); swap(p); x = p.getX(); y = p.getY(); System.out.println(x + " " + y); }

R7.23 parseInt(String s) toBinaryString(int i) toHexString(int i) toOctalString(int i) toString(int i) Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 4 valueOf(String s) They are static methods because these methods do not need an implicit parameter.

R7.25 It is not a good design because using public static fields are not a good idea. They can accidentally get overwritten in large programs. A better way to improve this is to have static methods System.getIn() and System.getOut() that return these streams.

R7.27 A qualified name is a name prefixed by its class name or by an object reference, such as Math.sqrt or other.balance. An unqualified name is a name without a class or object prefix such as account or getBalance

R7.29 To write a java program without import statements, the user needs to specify the path names of the classes that are used in the program /** An applet that computes and draws the intersection points of a circle and a line. */ public class IntersectionApplet extends java.applet.Applet { public IntersectionApplet() { String input = javax.swing.JOptionPane.showInputDialog("x:"); x = Integer.parseInt(input); }

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

double r = 100; // the radius of the circle

// draw the circle

java.awt.geom.Ellipse2D.Double circle = new java.awt.geom.Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS); g2.draw(circle);

// draw the vertical line

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

// compute the intersection points

double a = RADIUS; double b = RADIUS; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 5

double root = Math.sqrt(RADIUS * RADIUS - (x - a) * (x - a)); 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 double x; }

Programming Exercises

P7.1 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; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 6

}

private double value; private String name; }

Purse.java

/** A purse computes the total value of a collection of coins. */ public class Purse { /** Constructs an empty purse. */ public Purse() { total = 0; }

/** Add a coin to the purse. @param aCoin the coin to add */ public void add(Coin aCoin) { total = total + aCoin.getValue(); }

/** Get the total value of the coins in the purse. @return the sum of all coin values */ public double getTotal() { return total; }

private double total; }

PurseTest.java import javax.swing.JOptionPane;

/** This program tests the Purse class. */ public class PurseTest { public static void main(String[] args) { double NICKEL_VALUE = 0.05; double DIME_VALUE = 0.1; double QUARTER_VALUE = 0.25; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 7

Purse myPurse = new Purse();

boolean done = false; while (!done) { String input = JOptionPane.showInputDialog("Enter coin name or Cancel"); if (input == null) done = true; else { double value = 0; if (input.equals("nickel")) value = NICKEL_VALUE; else if (input.equals("dime")) value = DIME_VALUE; else if (input.equals("quarter")) value = QUARTER_VALUE; if (value != 0) { Coin c = new Coin(value, input); myPurse.add(c); double totalValue = myPurse.getTotal(); System.out.println("The total is " + totalValue); } } } System.exit(0); } }

P7.3 Geometry.java

/** This class implements the volume and surface area of a sphere, a cylinder, and a cone */ public class Geometry { /** Computes the volume of a sphere @param r the radius @return volume of sphere */ public static double sphereVolume(double r) { return (4.0 / 3.0) * Math.PI * r * r * r; }

/** Computes the surface area of a sphere @param r the radius @return surface area of a sphere */ Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 8

public static double sphereSurface(double r) { return 4.0 * Math.PI * r * r; }

/** Computes the volume of a cylinder @param r the radius @param h the height @return volume of a cylinder */ public static double cylinderVolume(double r, double h) { return h * Math.PI * r * r; }

/** Computes the surface area of a cylinder @param r the radius @param h the height @return surface area of a cylinder */ public static double cylinderSurface(double r, double h) { return (2.0 * r * Math.PI * h) + (2.0 * Math.PI * r * r); }

/** Computes the volume of a cone @param r the radius @param h the height @return volume of a cone */ public static double coneVolume(double r, double h) { return (1.0 / 3.0) * Math.PI * r * r * h; }

/** Computes the surface area of a cone @param r the radius @param h the height @return surface area of a cone */ public static double coneSurface(double r, double h) { return Math.PI * r * (h + r); } }

ExP7_3.java import javax.swing.JOptionPane;

/** This is a test driver for the Geometry class Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 9

to calculate the volume and surface area of a sphere, a cylinder, and a cone */ public class ExP7_3 { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter the radius:"); double r = Double.parseDouble(input); input = JOptionPane.showInputDialog( "Please enter the height:"); double h = Double.parseDouble(input);

System.out.println("The volume of the sphere is: " + Geometry.sphereVolume(r)); System.out.println("The surface area of the sphere is: " + Geometry.sphereSurface(r)); System.out.println("The volume of the cylinder is: " + Geometry.cylinderVolume(r, h)); System.out.println("The surface area of the cylinder is: " + Geometry.cylinderSurface(r, h)); System.out.println("The volume of the cone is: " + Geometry.coneVolume(r, h)); System.out.println("The surface area of the cone is: " + Geometry.coneSurface(r, h));

System.exit(0); } }

P7.5 EllipseHelper.java import java.awt.geom.Ellipse2D;

/** The standard API for the Ellipse does not provide methods to compute the area and perimeter of an Ellipse. Because we cannot add or modify library classes, we must provide our own helper class. It makes sense to use static methods here because these methods do not require an implicit parameter */ public class EllipseHelper { /** Computes the area of an ellipse @param e the ellipse @return area of the ellipse */ public static double area(Ellipse2D.Double e) { double a = e.getWidth() / 2; double b = e.getHeight() / 2; return Math.PI * a * b; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 10

}

/** Computes the perimeter of an ellipse @param e the ellipse @return the perimeter of the ellipse */ public static double perimeter(Ellipse2D.Double e) { double a = e.getWidth() / 2; double b = e.getHeight() / 2;

return Math.PI * (1.5 * (a + b) - Math.sqrt(a * b)); } }

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

/** This is a test driver for the Ellipse class */ public class ExP7_5 extends Applet { public void init() { String input = JOptionPane.showInputDialog( "Please enter the width:"); w = Double.parseDouble(input);

input = JOptionPane.showInputDialog( "Please enter the height:"); h = Double.parseDouble(input); }

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

Ellipse2D.Double e = new Ellipse2D.Double(0, 0, w, h); g2.draw(e);

g2.drawString("Perimeter: " + EllipseHelper.perimeter(e), 100, 260); g2.drawString("Area: " + EllipseHelper.area(e), 100, 290); }

double w; double h; } Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 11

P7.7 Geometry.java import java.awt.geom.Point2D; import java.awt.geom.Ellipse2D;

/** This class provides a method that determines if a point is inside an ellipse specified by the user */ public class Geometry { /** Computes if a point is inside an ellipse @param p a point @param e an ellipse @return true if p is inside e */ public static boolean isInside(Point2D.Double p, Ellipse2D.Double e) { double a = e.getWidth() / 2; double b = e.getHeight() / 2;

/* Note that the center of the ellipse has coordinates (e.getX() + a, e.getY() + b) */

double x = (p.getX() - e.getX() - a) / a; double y = (p.getY() - e.getY() - b) / b;

double xySquare = x * x + y * y;

return xySquare <= 1; } }

ExP7_7.java import javax.swing.JOptionPane; import java.awt.geom.Point2D; import java.awt.geom.Ellipse2D;

/** This is a test driver for the Ellipse class */ public class ExP7_7 { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter the width of the ellipse:"); double w = Double.parseDouble(input); input = JOptionPane.showInputDialog( "Please enter the height of the ellipse:"); double h = Double.parseDouble(input); Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 12

Ellipse2D.Double e = new Ellipse2D.Double(0, 0, w, h);

input = JOptionPane.showInputDialog( "Please enter the x-coordinate of the point:"); double x = Double.parseDouble(input); input = JOptionPane.showInputDialog( "Please enter the y-coordinate of the point:"); double y = Double.parseDouble(input); Point2D.Double p = new Point2D.Double(x, y);

System.out.print("The point is "); if (!Geometry.isInside(p, e)) System.out.print("not "); System.out.println("inside the ellipse.");

System.exit(0); } } P7.9 Letters.java import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D;

/** This class provides methods that implement the letters H, E, L, and O to form the words "HELLO" and "HOLE" */ public class Letters { /** Draws the letter H @param g2 the graphics context @param p the top left corner point */ public static void drawH(Graphics2D g2, Point2D.Double p) { double x = p.getX(); double y = p.getY(); Line2D.Double vert1 = new Line2D.Double(x, y, x, y + HEIGHT); Line2D.Double vert2 = new Line2D.Double(x + WIDTH, y, x + WIDTH, y + HEIGHT); Line2D.Double horiz = new Line2D.Double(x, y + HEIGHT / 2, x + WIDTH, y + HEIGHT / 2); g2.draw(vert1); g2.draw(vert2); g2.draw(horiz); }

/** Draws the letter E @param g2 the graphics context Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 13

@param p the top left corner point */ public static void drawE(Graphics2D g2, Point2D.Double p) { drawL(g2, p); double x = p.getX(); double y = p.getY(); Line2D.Double horiz1 = new Line2D.Double(x, y, x + WIDTH, y); Line2D.Double horiz2 = new Line2D.Double(x, y + HEIGHT / 2, x + WIDTH, y + HEIGHT / 2); g2.draw(horiz1); g2.draw(horiz2); }

/** Draws the letter L @param g2 the graphics context @param p the top left corner point */ public static void drawL(Graphics2D g2, Point2D.Double p) { double x = p.getX(); double y = p.getY(); Line2D.Double vert = new Line2D.Double(x, y, x, y + HEIGHT); Line2D.Double horiz = new Line2D.Double(x, y + HEIGHT, x + WIDTH, y + HEIGHT); g2.draw(vert); g2.draw(horiz); }

/** Draws the letter O @param g2 the graphics context @param p the top left corner point */ public static void drawO(Graphics2D g2, Point2D.Double p) { double x = p.getX(); double y = p.getY(); Ellipse2D.Double e = new Ellipse2D.Double(x, y, WIDTH, HEIGHT); g2.draw(e); }

private static final int WIDTH = 30; private static final int HEIGHT = 50; } import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Point2D;

ExP7_9.java Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 14

/** This is a test driver for the Helo class */ public class ExP7_9 extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g;

final int WIDTH = 30; final int HEIGHT = 50; final int SPACING = 5;

double x = 0; double y = 0;

Letters myLetters = new Letters();

myLetters.drawH(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawE(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawL(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawL(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawO(g2, new Point2D.Double(x, y)); x = 0;

y = y + HEIGHT + SPACING;

myLetters.drawH(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawO(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawL(g2, new Point2D.Double(x, y)); x = x + WIDTH + SPACING;

myLetters.drawE(g2, new Point2D.Double(x, y)); } }

P7.11 Digit.java

/** This class provides a method to translate a numeric zip code to its bar code equivalent */ Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 15 public class Digit { /** Constructs a Digit object with a numeric zip code @param n the zip code number (Precondition: 0 <= n && n <= 9) */ public Digit(int n) { zip = n; }

/** Converts the zip code number to its bar code equivalent @return bar the equivalent of the number */ public String getCode() { String bar = ""; if (zip == 1) bar = ":::||"; else if (zip == 2) bar = "::|:|"; else if (zip == 3) bar = "::||:"; else if (zip == 4) bar = ":|::|"; else if (zip == 5) bar = ":|:|:"; else if (zip == 6) bar = ":||::"; else if (zip == 7) bar = "|:::|"; else if (zip == 8) bar = "|::|:"; else if (zip == 9) bar = "|:|::"; else bar = "||:::";

return bar; }

private int zip; }

BarCode.java

/** This class provides a method to convert numbers in a zip code to a bar code */ public class BarCode { /** Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 16

Constructs a BarCode object @param n the zip code (Precondition: 0 <= n && n <= 99999) */ public BarCode(int n) { zip = n; }

/** Make 5 digit objects and concatenate their codes and add frame bars @return barCode the bar code equivalent */ public String getCode() { String barCode = "|"; int sum = 0; int temp = 0;

temp = zip / 10000; sum = sum + temp; Digit d1 = new Digit(temp); barCode = barCode + d1.getCode(); zip = zip % 10000;

temp = zip / 1000; sum = sum + temp; Digit d2 = new Digit(temp); barCode = barCode + d2.getCode(); zip = zip % 1000;

temp = zip / 100; sum = sum + temp; Digit d3 = new Digit(temp); barCode = barCode + d3.getCode(); zip = zip % 100;

temp = zip / 10; sum = sum + temp; Digit d4 = new Digit(temp); barCode = barCode + d4.getCode(); zip = zip % 10;

temp = zip; sum = sum + temp; Digit d5 = new Digit(temp); barCode = barCode + d5.getCode();

temp = 10 - (sum % 10); Digit d6 = new Digit(temp); barCode = barCode + d6.getCode() + "|";

return barCode; }

private int zip; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 17

}

ExP7_11.java import javax.swing.JOptionPane;

/** This is a test driver for BarCode and Digit class */ public class ExP7_11 { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter a five-digit zip code: "); int num = Integer.parseInt(input);

BarCode bc = new BarCode(num); String code = bc.getCode();

System.out.println("The barcode of the zip is: " + code);

System.exit(0); } }

P7.13 Digit.java

/** This class provides a method to decode a segment of a bar code */ public class Digit { /** Constructs a Digits object @param aCode the bar code equivalent of a numeric zip code */ public Digit(String aCode) { code = aCode;

}

/** Translates the barcode to its numerical value @return the numeric value or -1 if the code is illegal */ public int getCode() { if (code.equals(":::||")) return 1; else if (code.equals("::|:|")) return 2; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 18

else if (code.equals("::||:")) return 3; else if (code.equals(":|::|")) return 4; else if (code.equals(":|:|:")) return 5; else if (code.equals(":||::")) return 6; else if (code.equals("|:::|")) return 7; else if (code.equals("|::|:")) return 8; else if (code.equals("|:|::")) return 9; else if (code.equals("||:::")) return 0; else return -1; }

public boolean isValid() { return false; }

private String code; }

BarCode.java

/** This class provides a method to use the bar code from a string input and return a numeric zip code equivalent */ public class BarCode { /** Constructs a BarCode object @param aCode the string input */ public BarCode(String aCode) { code = aCode; }

/** Break the string input code into segments and translate to numeric code @return the bar code */ public int getCode() { if (code.length() != 2 + 6 * DIGITLENGTH) return -1; if (!code.substring(0, 1).equals("|")) return -1; Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 19

int i = 1; int sum = 0; int dsum = 0;

String codeDigit = code.substring(i, i + DIGITLENGTH); Digit d1 = new Digit(codeDigit); int val = d1.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1;

sum = sum + val * 10000; dsum = dsum + val;

codeDigit = code.substring(i, i + DIGITLENGTH); Digit d2 = new Digit(codeDigit); val = d2.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1; sum = sum + val * 1000; dsum = dsum + val;

codeDigit = code.substring(i, i + DIGITLENGTH); Digit d3 = new Digit(codeDigit); val = d3.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1; sum = sum + val * 100; dsum = dsum + val;

codeDigit = code.substring(i, i + DIGITLENGTH); Digit d4 = new Digit(codeDigit); val = d4.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1; sum = sum + val * 10; dsum = dsum + val;

codeDigit = code.substring(i, i + DIGITLENGTH); Digit d5 = new Digit(codeDigit); val = d5.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1; sum = sum + val; dsum = dsum + val;

codeDigit = code.substring(i, i + DIGITLENGTH); Digit d6 = new Digit(codeDigit); Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 20

val = d6.getCode(); i = i + DIGITLENGTH;

if (val < 0) return -1; dsum = dsum + val;

if (dsum % 10 != 0) return -1;

if (!code.substring(i, i + 1).equals("|")) return -1;

return sum; }

public boolean isValid() { return true; }

private final int DIGITLENGTH = 5;

private String code;

}

ExP7_13.java import javax.swing.JOptionPane;

/** This is a test driver for BarCode and Digit class */ public class ExP7_13 { public static void main(String[] args) { String code = JOptionPane.showInputDialog( "Please enter bar code: ");

BarCode bc = new BarCode(code);

int val = bc.getCode();

if (val >= 0) System.out.println("The zip code is: " + val); else System.out.println("Incorrect bar code data");

System.exit(0); } } P7.15 Greeter.java Solutions Manual: Chapter 7 Big Java, by Cay Horstmann 21 package com.yahoo.janedoe.example; public class Greeter { public Greeter(String aName, String anAdjective) { name = aName; adj = anAdjective; }

public void getGreeting() { System.out.println(name + ", you are the most " + adj + " person in the world!"); }

private String name; private String adj; }

GreeterTest.java import javax.swing.JOptionPane; package com.yahoo.janedoe.example; public class GreeterTest { public static void main(String[] args) { String name = JOptionPane.showInputDialog( "Please enter your name:"); String adjective = JOptionPane.showInputDialog( "Please enter an adjective describing yourself:");

Greeter g = new Greeter(name, adjective);

g.getGreeting();

System.exit(0); } }

Recommended publications