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

Review Exercises

R3.1 2  s = s0 + v0t + 1/2 gt s = s0 + v0 * t + 0.5 * g * t * t; 2 2  G = 4 PI a / P (m1 + m2) G = 4 * Math.pow(Math.PI, 2) * a / (Math.pow(P, 2) * (m1 + m2));  FV = PV . (1 + INT / 100)YRS FV = PV * Math.pow((1 + INT / 100), YRS);  c = (a2 + b2 - 2abcosg)1/2 c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) - 2 * a * b * Math.cos(gamma));

R3.3 The numerator is divided by 2, then multiplied by a, rather than divided by (2 * a). Parentheses in the denominator fix the problem: x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);

R3.5 /** This program tests the Purse class. */ import java.text.*; public class PurseTest { public static void main(String[] args) { Purse myPurse = new Purse();

myPurse.addNickels(3);

myPurse.addDimes(2);

myPurse.addQuarters(1);

NumberFormat formatter = NumberFormat.getCurrencyInstance();

System.out.println(formatter.format(myPurse.getTotal())); } } The program prints the total as 0.6000000000000001 because it is of type double. The user may want to use the NumberFormat class in the java.text package, which can be used to format a number to any amount of decimal places. Specifically, the getCurrencyInstance method of the NumberFormat class can to be generate Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 2 a currency value. See Advance Topic 3.5.

R3.7 In the first assignment, n = (int)(x + 0.5) 0.5 is added to x before being converted to an integer. In the second assignment, n = (int)Math.round(x); x will either be rounded up or down.

The difference between the two is that the first assigment will not work for x < 0.

For example, if x = -0.99, then x + 0.5 is -0.49 which gets rounded to 0 instead of -1.

R3.9 x = 2; y = x + x; Computes y = 2 + 2 = 4 s = "2"; t = s + s; Computes t = "2" + "2" = "22"

R3.11 (a) Integer.parseInt("" + x) is the same as x. True. x is converted to a string, then concatenated to the empty string. parseInt converts that string back to an integer, which is the same as the original value of x. (b) "" + Integer.parseInt(s) is the same as s. False. If s doesn't contain a number, then parseInt will fail. Even if s contains a number, the resulting string can be different. e.g. s = "0.50" yields the integer 0.5, which turns into the string "0.5", which is a different string (c) s.substring(0, s.length()) is the same as s. True. We are extracting all characters of s.

R3.13 int last = n % 10; Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 3

The idea to get the first number is to compute 10 raised to the log(n) power, then divide. However, Math.log computes the natural log ln, so we must get the decimal log as ln(x)/ln(10). double logn = Math.log(n) / Math.log(10); int ndigits = (int)logn; int pow10 = (int)Math.pow(10, ndigits); int first = n / pow10;

R3.15 A final variable is a variable whose contents cannot changed once it is initialized. That is, the value is constant.

You can actually define a final variable without supplying it's value. final int N; // other statements . . . N = 5; // after this initialization, N cannot change again But this is not good practice. Just supply the initialization value when you define the final variable.

R3.17 Copying numbers and copying object references uses the same type of commands. For example, double balance1 = 1000; double balance2 = balance1; balance2 = balance2 + 500; BankAccount account1 = new BankAccount(1000); BankAccount account2 = account1; account2.deposit(500);

The difference in this code is that the number variables hold values and the object variables hold references to another object. This means that the number variables are independent of each other once they are copied. The object variables, on the other hand, refer to each other, meaning that changing one variable results in changing the its reference also.

The result of copying the number variables above is: balance1 = 1000; balance2 = 1500; The result of copying the object variables is: account1 = 1500; account2 = 1500;

Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 4

R3.19 It is not a problem in sharing string references because strings are immutable. None of the methods of the String class change the state of the the String object.

Programming Exercises P3.1 Purse.java

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

/** Add pennies to the purse. @param count the number of pennies to add */ public void addPennies(int count) { pennies = pennies + count; }

/** Add nickels to the purse. @param count the number of nickels to add */ public void addNickels(int count) { nickels = nickels + count; }

/** Add dimes to the purse. @param count the number of dimes to add */ public void addDimes(int count) { dimes = dimes + count; } Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 5

/** Add quarters to the purse. @param count the number of quarters to add */ public void addQuarters(int count) { quarters = quarters + count; }

/** Add dollars to the purse. @param count the number of dollars to add */ public void addDollars(int count) { dollars = dollars + count; }

/** Get the total value of the coins in the purse. @return the sum of all coin values */ public double getTotal() { return pennies * PENNY_VALUE + nickels * NICKEL_VALUE + dimes * DIME_VALUE + quarters * QUARTER_VALUE + dollars * DOLLAR_VALUE; }

// constants private static final double PENNY_VALUE = 0.01; private static final double NICKEL_VALUE = 0.05; private static final double DIME_VALUE = 0.1; private static final double QUARTER_VALUE = 0.25; private static final double DOLLAR_VALUE = 1.0;

// instance variables private int pennies; private int nickels; private int dimes; private int quarters; private int dollars; }

ExP3_1.java /** This program tests the Purse class. */ public class ExP3_1 { public static void main(String[] args) { Purse myPurse = new Purse(); Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 6

myPurse.addPennies(107);

myPurse.addNickels(3);

myPurse.addDimes(2);

myPurse.addQuarters(1);

myPurse.addDollars(5);

double totalValue = myPurse.getTotal();

System.out.print("The total is "); System.out.println(totalValue); } }

P3.3 PowerGenerator.java

/** A PowerGenerator computes a number to the tenth power */ public class PowerGenerator { /** Constructs a power generator @param aFactor the power of the factor */ public PowerGenerator(int aFactor) { number = 1; power = aFactor; }

/** Computes the next power @return number the next value of applying the power */ public double nextPower() { number = number * power; return number; }

// instance variables private double number; private int power; }

PowerGeneratorTest.java

/** This program tests the PowerGenerator class. Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 7

*/ public class PowerGeneratorTest { public static void main(String[] args) { PowerGenerator myGenerator = new PowerGenerator(10);

System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); System.out.println(myGenerator.nextPower()); } }

P3.5 DataSet.java /** A DataSet computes the total and average value of a collection of numbers. */ public class DataSet { /** Constructs an empty data set. */ public DataSet() { total = 0; count = 0; }

/** Add the values @param x the value to be added */ public void addValue(int x) { count++;

total = total + x; }

/** Computes the sum of the values. @return the sum of the values */ public int getSum() { Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 8

return total; }

/** Computes the average of the values. @return the average of the values */ public double getAverage() { return (double)(total) / count; }

// instance variables private int total; private int count; }

DataSetTest.java /** This program tests the DataSet class. */ import javax.swing.JOptionPane; public class DataSetTest { public static void main(String[] args) { DataSet myDataSet = new DataSet();

String input = JOptionPane.showInputDialog( "Please enter the first number:"); int number1 = Integer.parseInt(input);

input = JOptionPane.showInputDialog( "Please enter the second number:"); int number2 = Integer.parseInt(input);

input = JOptionPane.showInputDialog( "Please enter the third number:"); int number3 = Integer.parseInt(input);

input = JOptionPane.showInputDialog( "Please enter the fourth number:"); int number4 = Integer.parseInt(input);

myDataSet.addValue(number1); myDataSet.addValue(number2); myDataSet.addValue(number3); myDataSet.addValue(number4);

System.out.println("The sum is " + myDataSet.getSum()); System.out.println("The average is " + myDataSet.getAverage());

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

DataSetTestConsole.java /** This program tests the DataSet class using a console. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class DataSetTestConsole { public static void main(String[] args) throws IOException { DataSet myDataSet = new DataSet();

BufferedReader console = new BufferedReader( new InputStreamReader(System.in));

System.out.println("Please enter the first number:"); String input1 = console.readLine(); int number1 = Integer.parseInt(input1);

System.out.println("Please enter the second number:"); String input2 = console.readLine(); int number2 = Integer.parseInt(input2);

System.out.println("Please enter the third number:"); String input3 = console.readLine(); int number3 = Integer.parseInt(input3);

System.out.println("Please enter the fourth number:"); String input4 = console.readLine(); int number4 = Integer.parseInt(input4);

myDataSet.addValue(number1); myDataSet.addValue(number2); myDataSet.addValue(number3); myDataSet.addValue(number4);

System.out.println("The sum is " + myDataSet.getSum()); System.out.println("The average is " + myDataSet.getAverage());

System.exit(0); } }

P3.7 Convertor.java /** A Convertor converts measurements in meters to miles, feet, and inches */ public class Convertor { /** Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 10

Constructs a converter that can convert between two units. @param aConversionFactor the factor with which to multiply to convert to the target unit */ public Convertor(double aConversionFactor) { factor = aConversionFactor; }

/** Converts from a source measurement to a target measurement. @param fromMeasurement the measurement @return the input value converted to the target unit */ public double convertTo(double fromMeasurement) { numberConversion = fromMeasurement;

return numberConversion / factor; }

// instance variables private double factor; private double numberConversion; }

ExP3_7.java /** This program tests the ClassName class. */ import javax.swing.JOptionPane; public class ExP3_7 { public static void main(String[] args) { final double MILE_TO_KM = 1.609; final double FEET_TO_KM = 0.000305; final double INCHES_TO_KM = 0.000025;

String input = JOptionPane.showInputDialog( "Please enter the meters:"); int meter = Integer.parseInt(input);

Convertor metersToMiles = new Convertor(1000 * MILE_TO_KM); Convertor metersToFeet = new Convertor(1000 * FEET_TO_KM); Convertor metersToInches = new Convertor(1000 * INCHES_TO_KM);

System.out.println("Meters to Miles: " + metersToMiles.convertTo(meter)); System.out.println("Meters to Feet: " + metersToFeet.convertTo(meter)); System.out.println("Meters to Inches: " + metersToInches.convertTo(meter));

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

} }

P3.9 SodaCan.java /** This class gives the volume and surface area of a soda can */ public class SodaCan { /** Construct a SodaCan @param aHeight the height of the soda can @param aDiameter the diameter of the soda can */ public SodaCan(double aHeight, double aDiameter) { double height = aHeight; double diameter = aDiameter; double radius = diameter / 2; volume = Math.PI * Math.pow(radius, 2) * height; surfaceArea = 2 * Math.PI * radius * height; }

/** Gets the volume of a soda can @return volume of the soda can */ public double getVolume() { return volume; }

/** Gets the surface area of a soda can @return surface area of the soda can */ public double getSurfaceArea() { return surfaceArea; }

// instance variables double volume; double surfaceArea; }

ExP3_9.java /** This program tests the SodaCan class. */ import javax.swing.JOptionPane; public class ExP3_9 { Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 12

public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter the height of the soda can:"); double height = Double.parseDouble(input);

input = JOptionPane.showInputDialog( "Please enter the diameter of the soda can:"); double diameter = Double.parseDouble(input);

SodaCan mySodaCan = new SodaCan(height, diameter);

System.out.println("The volume of the soda can with height " + height + " and diameter \n" + diameter + " is " + mySodaCan.getVolume());

System.out.println("The surface area of the soda can is " + mySodaCan.getSurfaceArea());

System.exit(0); } }

P3.11 Cashier.java /** A Cashier computes the change given to a customer */ public class Cashier { /** Construct the coin values the cashier uses to provide change */ public Cashier() { pennies = 1; nickels = 5; dimes = 10; quarters = 25; dollars = 100; }

/** Sets the amount that is due @param anAmountDue the amount due */ public void setAmountDue(double anAmountDue) { amountDue = anAmountDue; }

/** Amount received from customer @param _received the amount received from the customer */ public void receive(double amountReceived) Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 13

{ received = amountReceived; }

/** Amount in dollars returned @return number of dollars */ public double returnDollars() { change = (int)(dollars * (received - amountDue)); return change / dollars; }

/** Amount in quarters returned @return number of quarters */ public double returnQuarters() { change = change % dollars; return change / quarters; }

/** Amount in dimes returned @return number of dimes */ public double returnDimes() { change = change % quarters; return change / dimes; }

/** Amount in nickels returned @return number of nickels */ public double returnNickels() { change = change % dimes; return change / nickels; }

/** Amount in pennies returned @return number of pennies */ public double returnPennies() { return change % nickels; }

// instance variables private int pennies; private int nickels; private int dimes; Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 14

private int quarters; private int dollars; private int change; private double amountDue; private double received; }

ExP3_11.java /** This program tests the Cashier class. */ public class ExP3_11 { public static void main(String[] args) { Cashier harry = new Cashier();

harry.setAmountDue(9.37); harry.receive(10);

double dollars = harry.returnDollars(); double quarters = harry.returnQuarters(); double dimes = harry.returnDimes(); double nickels = harry.returnNickels(); double pennies = harry.returnPennies();

System.out.println( "Give the customer \n" + dollars + " dollars,\n" + quarters + " quarters,\n" + dimes + " dimes,\n" + nickels + " nickels,\n" + pennies + " pennies\n"); } }

P3.13 QuadraticEquation.java public class QuadraticEquation { /** 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 */ public QuadraticEquation(double coefficientA, double coefficientB, double coefficientC) { a = coefficientA; b = coefficientB; c = coefficientC; root = Math.sqrt(b * b -4 * a * c); }

/** Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 15

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

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

// instance variables double a; double b; double c; double root; }

QuadraticEquationTest.java /** This program tests the QuadraticEquation class. */ import javax.swing.JOptionPane; public class QuadraticEquationTest { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter coefficient a:"); int a = Integer.parseInt(input);

input = JOptionPane.showInputDialog( "Please enter coefficient b:"); int b = Integer.parseInt(input);

input = JOptionPane.showInputDialog( "Please enter coefficient c:"); int c = Integer.parseInt(input);

QuadraticEquation myEquation = new QuadraticEquation(a, b, c);

System.out.println(myEquation.getSolution1()); System.out.println(myEquation.getSolution2());

System.exit(0); } }

P3.15 Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 16

LetterH.java public class LetterH { /** Constructs a large letter H */ public LetterH() { }

/** Gets the large letter H @return large letter H */ public String getLetter() { return "* *\n* *\n*****\n* *\n* *\n"; } }

LetterE.java public class LetterE { /** Constructs a large letter E */ public LetterE() { }

/** Gets the large letter E @return large letter E */ public String getLetter() { return "*****\n*\n*****\n*\n*****\n"; } }

LetterL.java public class LetterL { /** Constructs a large letter L */ public LetterL() { }

/** Gets the large letter L @return large letter L */ public String getLetter() { return "*\n*\n*\n*\n*****\n"; Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 17

} }

LetterO.java public class LetterO { /** Constructs a large letter O */ public LetterO() { }

/** Gets the large letter O @return large letter O */ public String getLetter() { return " ***\n* *\n* *\n* *\n ***\n"; } }

ExP3_15.java /** This program tests the LetterH, LetterE, LetterL, LetterO class. */ public class ExP3_15 { public static void main(String[] args) { LetterH myLetterH = new LetterH(); LetterE myLetterE = new LetterE(); LetterL myLetterL = new LetterL(); LetterO myLetterO = new LetterO();

System.out.println(myLetterH.getLetter()); System.out.println(myLetterE.getLetter()); System.out.println(myLetterL.getLetter()); System.out.println(myLetterL.getLetter()); System.out.println(myLetterO.getLetter()); } } P3.17 Year.java public class Year { /** Constructs the date of Easter Sunday. */ public Year(int year) { int y = year; int a = y % 19; int b = y / 100; Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 18

int c = y % 100; int d = b / 4; int e = b % 4; int g = (8 * b + 13) / 25; int h = (19 * a + b - d - g + 15) % 30; int j = c / 4; int k = c % 4; int m = (a + 11 * h) / 319; int r = (2 * e + 2 * j - k - h + m + 32) % 7; n = (h - m + r + 90) / 25; p = (h - m + r + n + 19) % 32; }

/** Gets the month of Easter Sunday @return month of Easter Sunday */ public int getEasterSundayMonth() { return n; }

/** Gets the date of Easter Sunday @return date of Easter Sunday */ public int getEasterSundayDay() { return p; }

// instance variables int n; int p; }

ExP3_17.java /** This program tests the Year class. */ import javax.swing.JOptionPane; public class ExP3_17 { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Please enter the year:"); int year = Integer.parseInt(input);

Year myYear = new Year(year);

System.out.println("The month of Easter Sunday is " + myYear.getEasterSundayMonth() + " " + "and the date is " + myYear.getEasterSundayDay()); Solutions Manual: Chapter 3 Big Java, by Cay Horstmann 19

System.exit(0); } }