Sie sind auf Seite 1von 24

Chapter 5: Enhancing Classes

Solutions
Multiple Choice
Solutions
1. a
2. c
3. a
4. b
5. e
6. c
7. e
8. d
9. e
10. d

True/False
Solutions
1. T
2. T
3. F
4. F
5. T
6. T
7. F
8. T
9. T
10. T

Short Answer Solutions


5.1 What is output by the following code?
String s1 = hello ;
String s2 = s1;
s2 = s2 + there ;
System.out.println(s1);
System.out.println(s2);
hello
hello there

5.2 Discuss how Java passes parameters to a method. Is this technique the same for primitive types and objects?
Explain.
Java passes all parameters by value. This means that the current value of the
actual parameter is copied into the formal parameter in the method header. This
technique is consistent between primitive types and objects because object
references rather than objects themselves are passed. When an object (actually,
an object reference) is passed, the current value of the reference is copied into
the corresponding formal parameter in the method header.

5.3

Explain why a static method cannot refer to an instance variable.


A static method is invoked through a class rather than through an object of the
class. No object of the class needs to be instantiated in order to invoke a
static method. If no object is instantiated, no instance variable exists. Hence,
a static method cannot refer to an instance variable.

5.4 Can a class implement two interfaces that each contain the same method signature? Explain.
Yes, a class can implement two interfaces each of which contains the same method
signature. The class which implements an interface provides method
implementations for each of the abstract methods defined in the interface. In
satisfying the requirements for a method of one interface, it simultaneously
satisfies the requirements for a method with the same signature in another
interface.

2007 Pearson Education

S 78

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 79

5.5 Create an interface called Visible that includes two methods: makeVisible and makeInvisible. Both
methods should take no parameters and should return a boolean result. Describe how a class might implement
this interface.
public interface Visible
{
public boolean makeVisible ();
public boolean makeInvisible ();
}
A class implementing Visible would begin with
public class Icon implements Visible
and would contain at least two methods (makeVisible and makeInvisible), which take
no parameters and return a boolean value indicating the success of the method.

5.6
Create an interface called VCR with methods that represent what a video cassette recorder does (play, stop,
etc.). Define the method signatures any way you want. Describe how a class might implement this interface.
public interface VCR
{
public void play ();
public void pause ();
public void stop ();
public void rewind ();
public void fastforward ();
}
A class implementing VCR would include implements VCR in the class header and
would implement each of the five methods from the VCR interface. The methods would
behave as indicted by their name. For example, fastforward causes the VCR to start
fast-forwarding. This keeps going until the stop method is called or another
method such as play or rewind is called.

5.7
Given the Num and ParameterTester classes listed earlier in the chapter, what is the result of executing the
following lines of code?
ParameterTester myTester = new ParameterTester();
int anInteger = 27;
Num aNum = new Num(38);
Num anotherNum = new Num(49);
myTester.changeValues(anInteger, aNum, anotherNum);
System.out.println(anInteger: + anInteger);
System.out.println(aNum: + aNum);
System.out.println(anotherNum: + anotherNum);
Before changing the values:
f1
f2
f3
27
38
49
After changing the values:
f1
f2
f3
999
888
777
anInteger: 27
aNum: 888
anotherNum: 49

Programming Project Solutions


5.1 PigLatin2
//********************************************************************
// PigLatin2.java
Author: Lewis/Loftus/Cocking
2007 Pearson Education

S 80

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

//
// Solution to Programming Project 5.1
//********************************************************************
import java.util.Scanner;
public class PigLatin2
{
//----------------------------------------------------------------// Reads sentences and translates them into Pig Latin.
//----------------------------------------------------------------public static void main (String[] args)
{
String sentence, result, another;
Scanner scan = new Scanner (System.in);
do
{
System.out.println ();
System.out.println ("Enter a sentence (no punctuation):");
sentence = scan.nextLine();
System.out.println ();
result = PigLatinTranslator2.translate (sentence);
System.out.println ("That sentence in Pig Latin is:");
System.out.println (result);
System.out.println ();
System.out.print ("Translate another sentence (y/n)? ");
another = scan.nextLine();
}
while (another.equalsIgnoreCase("y"));
}
}
5.1 PigLatinTranslator2
//********************************************************************
// PigLatinTranslator2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.1
//********************************************************************
import java.util.StringTokenizer;
public class PigLatinTranslator2
{
//----------------------------------------------------------------// Translates a sentence of words into Pig Latin.
//----------------------------------------------------------------public static String translate (String sentence)
{
String result = "";
sentence = sentence.toLowerCase();
StringTokenizer tokenizer = new StringTokenizer (sentence);
while (tokenizer.hasMoreTokens())
{
result += translateWord (tokenizer.nextToken());
result += " ";
}
return result;
}
//---------------------------------------------------------------- 2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

// Translates one word into Pig Latin. If the word begins with a
// vowel, the suffix "yay" is appended to the word. Otherwise,
// the first letter or two are moved to the end of the word,
// and "ay" is appended.
//----------------------------------------------------------------private static String translateWord (String word)
{
String result = "";
if (beginsWithVowel(word))
result = word + "yay";
else
if (beginsWithPrefix(word))
result = word.substring(2) + word.substring(0,2) + "ay";
else
result = word.substring(1) + word.charAt(0) + "ay";
return result;
}
//----------------------------------------------------------------// Determines if the specified word begins with a vowel.
//----------------------------------------------------------------private static boolean beginsWithVowel (String word)
{
String vowels = "aeiouAEIOU";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}
//----------------------------------------------------------------// Determines if the specified word begins with a particular
// two-character prefix.
//----------------------------------------------------------------private static boolean beginsWithPrefix (String str)
{
return ( str.startsWith ("bl") || str.startsWith ("pl") ||
str.startsWith ("br") || str.startsWith ("pr") ||
str.startsWith ("ch") || str.startsWith ("sh") ||
str.startsWith ("cl") || str.startsWith ("sl") ||
str.startsWith ("cr") || str.startsWith ("sp") ||
str.startsWith ("dr") || str.startsWith ("sr") ||
str.startsWith ("fl") || str.startsWith ("st") ||
str.startsWith ("fr") || str.startsWith ("th") ||
str.startsWith ("gl") || str.startsWith ("tr") ||
str.startsWith ("gr") || str.startsWith ("wh") ||
str.startsWith ("kl") || str.startsWith ("wr") ||
str.startsWith ("ph") );
}
}
5.2 Rational
//********************************************************************
// Rational.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.2
//
// Represents one rational number with a numerator and denominator.
//********************************************************************
public class Rational implements Comparable
{
private int numerator, denominator;
private final double TOLERANCE = 0.0001;
2007 Pearson Education

S 81

S 82

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

//----------------------------------------------------------------// Sets up the rational number by ensuring a nonzero denominator


// and making only the numerator signed.
//----------------------------------------------------------------public Rational (int numer, int denom)
{
if (denom == 0)
denom = 1;
// Make the numerator "store" the sign
if (denom < 0)
{
numer = numer * -1;
denom = denom * -1;
}
numerator = numer;
denominator = denom;
reduce();
}
//----------------------------------------------------------------// Returns the numerator of this rational number.
//----------------------------------------------------------------public int getNumerator ()
{
return numerator;
}
//----------------------------------------------------------------// Returns the denominator of this rational number.
//----------------------------------------------------------------public int getDenominator ()
{
return denominator;
}
//----------------------------------------------------------------// Returns the reciprocal of this rational number.
//----------------------------------------------------------------public Rational reciprocal ()
{
return new Rational (denominator, numerator);
}
//----------------------------------------------------------------// Adds this rational number to the one passed as a parameter.
// A common denominator is found by multiplying the individual
// denominators.
//----------------------------------------------------------------public Rational add (Rational op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int sum = numerator1 + numerator2;
return new Rational (sum, commonDenominator);
}
//----------------------------------------------------------------// Subtracts the rational number passed as a parameter from this
// rational number.
//---------------------------------------------------------------- 2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

public
{
int
int
int
int

Rational subtract (Rational op2)


commonDenominator = denominator * op2.getDenominator();
numerator1 = numerator * op2.getDenominator();
numerator2 = op2.getNumerator() * denominator;
difference = numerator1 - numerator2;

return new Rational (difference, commonDenominator);


}
//----------------------------------------------------------------// Multiplies this rational number by the one passed as a
// parameter.
//----------------------------------------------------------------public Rational multiply (Rational op2)
{
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();
return new Rational (numer, denom);
}
//----------------------------------------------------------------// Divides this rational number by the one passed as a parameter
// by multiplying by the reciprocal of the second rational.
//----------------------------------------------------------------public Rational divide (Rational op2)
{
return multiply (op2.reciprocal());
}
//----------------------------------------------------------------// Determines if this rational number is equal to the one passed
// as a parameter. Assumes they are both reduced.
//----------------------------------------------------------------public boolean equals (Rational op2)
{
return ( numerator == op2.getNumerator() &&
denominator == op2.getDenominator() );
}
//----------------------------------------------------------------// Returns this rational number as a string.
//----------------------------------------------------------------public String toString ()
{
String result;
if (numerator == 0)
result = "0";
else
if (denominator == 1)
result = numerator + "";
else
result = numerator + "/" + denominator;
return result;
}
//----------------------------------------------------------------// Implements method from Comparable interace.
//----------------------------------------------------------------public int compareTo(Object o)
{
Rational r = (Rational)o;
2007 Pearson Education

S 83

S 84

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

double thisValue = (double)numerator / denominator;


double otherValue = (double)r.numerator / r.denominator;
if (Math.abs(thisValue - otherValue) < TOLERANCE)
return 0;
else
if (thisValue > otherValue)
return 1;
else
return -1;
}
//----------------------------------------------------------------// Reduces this rational number by dividing both the numerator
// and the denominator by their greatest common divisor.
//----------------------------------------------------------------private void reduce ()
{
if (numerator != 0)
{
int common = gcd (Math.abs(numerator), denominator);
numerator = numerator / common;
denominator = denominator / common;
}
}
//----------------------------------------------------------------// Computes and returns the greatest common divisor of the two
// positive parameters. Uses Euclid's algorithm.
//----------------------------------------------------------------private int gcd (int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return num1;
}
}
5.2 RationalNumbers
//********************************************************************
// RationalNumbers.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.2
//
// Driver to exercise the use of multiple Rational objects.
//********************************************************************
public class RationalNumbers
{
//----------------------------------------------------------------// Creates some rational number objects and performs various
// operations on them.
//----------------------------------------------------------------public static void main (String[] args)
{
Rational r1 = new Rational (6, 8);
Rational r2 = new Rational (1, 3);
Rational r3, r4, r5, r6, r7;
System.out.println ("First rational number: " + r1);
System.out.println ("Second rational number: " + r2);
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 85

int compareValue = r1.compareTo(r2);


if (compareValue == 0)
System.out.println ("r1 and r2 are equal.");
else
if (compareValue < 0)
System.out.println ("r1 is less than r2");
else
System.out.println("r1 is greater than r2");
Rational r8 = new Rational (6, 7);
Rational r9 = new Rational (6, 7);
System.out.println ("\nr8 rational number: " + r8);
System.out.println ("r9 rational number: " + r9);
compareValue = r8.compareTo(r9);
if (compareValue == 0)
System.out.println ("r8 and r9 are equal.");
else
if (compareValue < 0)
System.out.println ("r8 is less than r9");
else
System.out.println("r8 is greater than r9");
Rational r10 = new Rational (4, 7);
Rational r11 = new Rational (5, 6);
System.out.println ("\nr10 rational number: " + r10);
System.out.println ("r11 rational number: " + r11);
compareValue = r10.compareTo(r11);
if (compareValue == 0)
System.out.println ("r10 and r11 are equal.");
else
if (compareValue < 0)
System.out.println ("r10 is less than r11");
else
System.out.println("r10 is greater than r11");
r3 = r1.reciprocal();
System.out.println ("\nThe reciprocal of r1 is: " + r3);
r4
r5
r6
r7

=
=
=
=

r1.add(r2);
r1.subtract(r2);
r1.multiply(r2);
r1.divide(r2);

System.out.println
System.out.println
System.out.println
System.out.println

("r1
("r1
("r1
("r1

+
*
/

r2:
r2:
r2:
r2:

"
"
"
"

+
+
+
+

r4);
r5);
r6);
r7);

}
}
Priority.java for 5.3, 5.4, & 5.5
//***************************************************************
// Priority.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.3, 5.4 & 5.5
//
//***************************************************************
2007 Pearson Education

S 86

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

public interface Priority


{
static final int MED_PRIORITY = 5;
static final int MAX_PRIORITY = 10;
static final int MIN_PRIORITY = 1;
//----------------------------------------------------------------// Sets the object's priority level
//----------------------------------------------------------------public void setPriority(int value);
//----------------------------------------------------------------// Returns the object's priority level
//----------------------------------------------------------------public int getPriority();
}
5.3 Task
//***************************************************************
// Task.java Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.3
//
//********************************************************************
public class Task implements Priority
{
private int priority;
String name;
//----------------------------------------------------------------// Sets up the task, assigning the task's name
//----------------------------------------------------------------public Task(String taskName)
{
name = taskName;
priority = MED_PRIORITY;
}
//----------------------------------------------------------------// Returns the Task's name
//----------------------------------------------------------------String getName()
{
return name;
}
//----------------------------------------------------------------// Sets the Task's priority level
//----------------------------------------------------------------public void setPriority(int value)
{
priority = value;
}
//----------------------------------------------------------------// Returns the Task's priority level
//----------------------------------------------------------------public int getPriority()
{
return priority;
}
}
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 87

5.3 TaskDriver
//***************************************************************
// TaskDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.3
//
//***************************************************************
public class TaskDriver
{
public static void main(String args[])
{
Task task1 = new Task("Write another Java program");
task1.setPriority(7);
Task task2 = new Task("Eat");
task2.setPriority(Priority.MIN_PRIORITY);
Task task3 = new Task("Attend class");
task3.setPriority(Priority.MAX_PRIORITY);
Task task4 = new Task("Sleep");
task4.setPriority(4);
System.out.println(" TO-DO\n------------");
System.out.println(task1.getName() + " \tpriority:
task1.getPriority());
System.out.println(task2.getName() + " \tpriority:
task2.getPriority());
System.out.println(task3.getName() + " \tpriority:
task3.getPriority());
System.out.println(task4.getName() + " \tpriority:
task4.getPriority());

" +
" +
" +
" +

}
}
5.4 Complexity
//***************************************************************
// Complexity.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.4
//***************************************************************
public interface Complexity
{
static final int MED_COMPLEXITY = 5;
static final int MAX_COMPLEXITY = 10;
static final int MIN_COMPLEXITY = 1;
//----------------------------------------------------------------// Sets the object's complexity level
//----------------------------------------------------------------public void setComplexity (int complexity);
//----------------------------------------------------------------// Returns the object's complexity level
//----------------------------------------------------------------public int getComplexity();
}
5.4 Task 2
//***************************************************************
// Task2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.4
//
2007 Pearson Education

S 88

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

//***************************************************************
public class Task2 implements Priority, Complexity
{
private int priority;
private int complexity;
String name;
//----------------------------------------------------------------// Sets up the task, assigning the task's name
//----------------------------------------------------------------public Task2(String taskName)
{
name = taskName;
priority = MED_PRIORITY;
}
//----------------------------------------------------------------// Returns the task's name
//----------------------------------------------------------------String getName()
{
return name;
}
//----------------------------------------------------------------// Sets the task's priority level
//----------------------------------------------------------------public void setPriority(int value)
{
priority = value;
}
//----------------------------------------------------------------// Returns the task's priority level
//----------------------------------------------------------------public int getPriority()
{
return priority;
}
//----------------------------------------------------------------// Sets the task's complexity level
//----------------------------------------------------------------public void setComplexity (int complexity)
{
this.complexity = complexity;
}
//----------------------------------------------------------------// Returns the task's complexity level
//----------------------------------------------------------------public int getComplexity()
{
return complexity;
}
}
5.4 TaskDriver2
//***************************************************************
// TaskDriver2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.4
//
//***************************************************************
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 89

public class TaskDriver2


{
public static void main(String args[])
{
Task2 task1 = new Task2("Write another Java program");
task1.setPriority(7);
task1.setComplexity(Complexity.MAX_COMPLEXITY);
Task2 task2 = new Task2("Eat");
task2.setPriority(Priority.MIN_PRIORITY);
task2.setComplexity(Complexity.MIN_COMPLEXITY);
Task2 task3 = new Task2("Attend class");
task3.setPriority(Priority.MAX_PRIORITY);
task3.setComplexity(Complexity.MED_COMPLEXITY);
Task2 task4 = new Task2("Sleep");
task4.setPriority(4);
task4.setComplexity(Complexity.MIN_COMPLEXITY);

System.out.println(" TO-DO\n------------");
System.out.println(task1.getName());
System.out.println("\tpriority: " + task1.getPriority()
task1.getComplexity());
System.out.println("");
System.out.println(task2.getName());
System.out.println("\tpriority: " + task2.getPriority()
task2.getComplexity());
System.out.println("");
System.out.println(task3.getName());
System.out.println("\tpriority: " + task3.getPriority()
task3.getComplexity());
System.out.println("");
System.out.println(task4.getName());
System.out.println("\tpriority: " + task4.getPriority()
task4.getComplexity());

+ ", complexity: "

+ ", complexity: "

+ ", complexity: "

+ ", complexity: "

}
}
5.5Complexity
//***************************************************************
// Complexity.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.4
//***************************************************************
public interface Complexity
{
static final int MED_COMPLEXITY = 5;
static final int MAX_COMPLEXITY = 10;
static final int MIN_COMPLEXITY = 1;
//----------------------------------------------------------------// Sets the object's complexity level
//----------------------------------------------------------------public void setComplexity (int complexity);
//----------------------------------------------------------------// Returns the object's complexity level
//----------------------------------------------------------------public int getComplexity();
}
5.5 Task3
2007 Pearson Education

S 90

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

//***************************************************************
// Task3.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.5
//
//***************************************************************
public class Task3 implements Priority, Complexity, Comparable
{
private int priority;
private int complexity;
String name;
//----------------------------------------------------------------// Sets up the task, assigning the task's name
//----------------------------------------------------------------public Task3(String taskName)
{
name = taskName;
priority = MED_PRIORITY;
}
//----------------------------------------------------------------// Returns the task's name
//----------------------------------------------------------------String getName()
{
return name;
}
//----------------------------------------------------------------// Sets the task's priority level
//----------------------------------------------------------------public void setPriority(int value)
{
priority = value;
}
//----------------------------------------------------------------// Returns the task's priority level
//----------------------------------------------------------------public int getPriority()
{
return priority;
}
//----------------------------------------------------------------// Sets the task's complexity level
//----------------------------------------------------------------public void setComplexity (int complexity)
{
this.complexity = complexity;
}
//----------------------------------------------------------------// Returns the task's complexity level
//----------------------------------------------------------------public int getComplexity()
{
return complexity;
}
//----------------------------------------------------------------// Compares two tasks based on priority
//----------------------------------------------------------------public int compareTo(Object o)
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 91

{
Task3 other = (Task3)o;
if (other.priority == this.priority)
return 0;
else
if (other.priority > this.priority)
return -1;
else
return 1;
}
}
5.5 TaskDriver3
//***************************************************************
// TaskDriver3.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.5
//
//***************************************************************
public class TaskDriver3
{
public static void main(String args[])
{
Task3 task1 = new Task3("Write another Java program");
task1.setPriority(7);
task1.setComplexity(Complexity.MAX_COMPLEXITY);
Task3 task2 = new Task3("Eat");
task2.setPriority(Priority.MIN_PRIORITY);
task2.setComplexity(Complexity.MIN_COMPLEXITY);
Task3 task3 = new Task3("Attend class");
task3.setPriority(Priority.MAX_PRIORITY);
task3.setComplexity(Complexity.MED_COMPLEXITY);
Task3 task4 = new Task3("Sleep");
task4.setPriority(4);
task4.setComplexity(Complexity.MIN_COMPLEXITY);

System.out.println(" TO-DO\n------------");
System.out.println(task1.getName());
System.out.println("\tpriority: " + task1.getPriority()
task1.getComplexity());
System.out.println("");
System.out.println(task2.getName());
System.out.println("\tpriority: " + task2.getPriority()
task2.getComplexity());
System.out.println("");
System.out.println(task3.getName());
System.out.println("\tpriority: " + task3.getPriority()
task3.getComplexity());
System.out.println("");
System.out.println(task4.getName());
System.out.println("\tpriority: " + task4.getPriority()
task4.getComplexity());

+ ", complexity: "

+ ", complexity: "

+ ", complexity: "

+ ", complexity: "

System.out.print("\nTASK:");
if (task1.compareTo(task2) == 0)
System.out.println(task1.getName() + " has the same priority as TASK:"
+ task2.getName());
else
if (task1.compareTo(task2) > 0)
System.out.println(task1.getName() + " has greater priority than
TASK:" + task2.getName());
2007 Pearson Education

S 92

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

else
System.out.println(task2.getName() + " has greater priority than
TASK:" + task1.getName());
System.out.print("\nTASK:");
if (task3.compareTo(task4) == 0)
System.out.println(task3.getName() + " has the same priority as TASK:"
+ task4.getName());
else
if (task3.compareTo(task4) > 0)
System.out.println(task3.getName() + " has greater priority than
TASK:" + task4.getName());
else
System.out.println(task4.getName() + " has greater priority than
TASK:" + task3.getName());
}
}
5.6 Lockable
//***************************************************************
// Lockable.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.6 & 5.7
//
//***************************************************************
public interface Lockable
{
//----------------------------------------------------------------// Sets the object's key
//----------------------------------------------------------------public void setKey(int key);
//----------------------------------------------------------------// Locks the object
//----------------------------------------------------------------public void lock(int key);
//----------------------------------------------------------------// Unlocks the object
//----------------------------------------------------------------public void unlock(int key);
//----------------------------------------------------------------// Returns true it the object is locked, else returns false
//----------------------------------------------------------------public boolean locked();
}
5.6 Coin
//***************************************************************
// Coin.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.6
//***************************************************************
import java.util.Random;
public class Coin implements Lockable
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

private
private
private
private
private

final int HEADS = 0;


final int TAILS = 1;
final int LOCK = 3;
boolean locked;
int coinKey;

private int face;


//----------------------------------------------------------------// Sets up the coin by flipping it initially.
//----------------------------------------------------------------public Coin ()
{
locked = false;
coinKey = 0;
flip();
}
//----------------------------------------------------------------// Flips the coin by randomly choosing a face value.
//----------------------------------------------------------------public void flip ()
{
if (!locked)
face = (int) (Math.random() * 2);
}
//----------------------------------------------------------------// Returns true if the current face of the coin is heads.
//----------------------------------------------------------------public boolean isHeads ()
{
return (face == HEADS);
}
//----------------------------------------------------------------// Returns the current face of the coin as a string.
//----------------------------------------------------------------public String toString()
{
if (!locked)
{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
else
return "LOCKED";
}
//----------------------------------------------------------------// Sets the object's key
//----------------------------------------------------------------public void setKey(int key)
{
if (!locked)
coinKey = key;
}
//----------------------------------------------------------------// Locks the object
2007 Pearson Education

S 93

S 94

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

//----------------------------------------------------------------public void lock(int key)


{
if (key == coinKey)
locked = true;
}
//----------------------------------------------------------------// Unlocks the object
//----------------------------------------------------------------public void unlock(int key)
{
if (key == coinKey)
locked = false;
}
//----------------------------------------------------------------// Returns true it the object is locked, else returns false
//----------------------------------------------------------------public boolean locked()
{
return locked;
}
}
5.6 TestCoin
//***************************************************************
// TestCoin.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Assignment 5.6
//********************************************************************
public class TestCoin
{
//----------------------------------------------------------------// Flips a coin multiple times and counts the number of heads
// and tails that result. Locks and unlocks coins
//----------------------------------------------------------------public static void main (String[] args)
{
final int NUM_FLIPS = 25;
int key = 10;
Coin myCoin = new Coin();
myCoin.setKey(key);

// instantiate the Coin object

for (int count=1; count <= NUM_FLIPS; count++)


{
myCoin.flip();
System.out.println(myCoin);
if (count % 10 == 0)
myCoin.lock(key);
else
if (count % 5 == 0)
myCoin.unlock(key);
}
}
}
5.7 Lockable
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 95

//***************************************************************
// Lockable.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.6 & 5.7
//
//***************************************************************
public interface Lockable
{
//----------------------------------------------------------------// Sets the object's key
//----------------------------------------------------------------public void setKey(int key);
//----------------------------------------------------------------// Locks the object
//----------------------------------------------------------------public void lock(int key);
//----------------------------------------------------------------// Unlocks the object
//----------------------------------------------------------------public void unlock(int key);
//----------------------------------------------------------------// Returns true it the object is locked, else returns false
//----------------------------------------------------------------public boolean locked();
}
5.7 Account
//***************************************************************
// Account.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.7
//***************************************************************
import java.text.NumberFormat;
public class Account implements Lockable
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035;

// interest rate of 3.5%

private long acctNumber;


private double balance;
private String name;
private int accountKey;
private boolean locked;
//----------------------------------------------------------------// Sets up the account by defining its owner and account number.
// Initial balance is set to zero
//----------------------------------------------------------------public Account (String owner, long account)
{
name = owner;
acctNumber = account;
balance = 0.0;
locked = false;
accountKey = 0;
2007 Pearson Education

S 96

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

}
//----------------------------------------------------------------// Sets up the account by defining its owner, account number,
// and initial balance.
//----------------------------------------------------------------public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
locked = false;
accountKey = 0;
}
//----------------------------------------------------------------// Validates the transaction. If sufficent funds exist, withdraws the
specified amount
// from the "from" account and deposits it into the "to" account returning
true,
// else does nothing and returns false.
//----------------------------------------------------------------public static boolean transfer (double amount, double fee, Account from,
Account to)
{
if (from.locked() || to.locked())
return false;
if (from.balance + fee < amount || amount < 0)
return false;
from.withdraw(amount, fee);
to.deposit(amount);
return true;
}
//----------------------------------------------------------------// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//----------------------------------------------------------------public double deposit (double amount)
{
if (locked)
return balance;
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//----------------------------------------------------------------// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//----------------------------------------------------------------public double withdraw (double amount, double fee)
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

if (locked)
return balance;
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
//----------------------------------------------------------------// Adds interest to the account and returns the new balance.
//----------------------------------------------------------------public double addInterest ()
{
if (locked)
return balance;
balance += (balance * RATE);
return balance;
}
//----------------------------------------------------------------// Returns the current balance of the account.
//----------------------------------------------------------------public double getBalance ()
{
return balance;
}
//----------------------------------------------------------------// Returns the account number.
//----------------------------------------------------------------public long getAccountNumber ()
{
return acctNumber;
}
//----------------------------------------------------------------// Returns a one-line description of the account as a string.
//----------------------------------------------------------------public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
//----------------------------------------------------------------// Sets the account's key
//---------------------------------------------------------------- 2007 Pearson Education

S 97

S 98

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

public void setKey(int key)


{
accountKey = key;
}
//----------------------------------------------------------------// Locks the account
//----------------------------------------------------------------public void lock(int key)
{
if (key == accountKey)
locked = true;
}
//----------------------------------------------------------------// Unlocks the account
//----------------------------------------------------------------public void unlock(int key)
{
if (key == accountKey)
locked = false;
}
//----------------------------------------------------------------// Returns true it the account is locked, else returns false
//----------------------------------------------------------------public boolean locked()
{
return locked;
}
}
5.8 SumProduct
//***************************************************************
// SumProduct.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.8
//
//***************************************************************
import javax.swing.JOptionPane;
public class SumProduct
{
//----------------------------------------------------------------// Uses dialog boxes to prompt a user for two integers. Displays
// the sum and the product of the integers. Allows the user to
// choose to process more pairs of numbers
//----------------------------------------------------------------public static void main (String args[])
{
String numString, result;
int num1, num2, again;
do
{
numString = JOptionPane.showInputDialog("Enter an integer: ");
num1 = Integer.parseInt(numString);
numString = JOptionPane.showInputDialog("Enter another integer: ");
num2 = Integer.parseInt(numString);
result = "You entered " + num1 + " and " + num2;
result += "\nThe sum of these numbers is " + (num1 + num2);
result += "\nThe product of these numbers is " + (num1 * num2);
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions

S 99

JOptionPane.showMessageDialog(null, result);
again = JOptionPane.showConfirmDialog(null, "Another?");
}
while (again == JOptionPane.YES_OPTION);
}
}
5.9 PalindromeTester
//***************************************************************
// PalindromeTester.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.9
//***************************************************************
import javax.swing.JOptionPane;
public class PalindromeTester
{
//----------------------------------------------------------------// Removes whitespace and punction from a string. Converts all
// characters to lowercase.
//----------------------------------------------------------------private static String convertString(String s)
{
String converted = "";
char current;
for (int i=0; i<s.length(); i++)
{
current = s.charAt(i);
if (Character.isLetterOrDigit(current)) // only count letters and
digits
{
if (Character.isUpperCase(current))

// convert to lowercase if

needed
current = Character.toLowerCase(current);
converted += current;
}
}
return converted;
}
//----------------------------------------------------------------// Tests strings to see if they are palindromes.
//----------------------------------------------------------------public static void main (String[] args)
{
String str, result, in;
int left, right;
int another;
do
{
in = JOptionPane.showInputDialog ("Enter a potential palindrome:");
str = convertString(in);
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right)
2007 Pearson Education

S 100

Lewis/Loftus/Cocking, 2/e: Chapter 5


Solutions

{
left++;
right--;
}
result = "\"" + in + "\"";
if (left < right)
result += " is NOT a palindrome.";
else
result += " IS a palindrome.";
JOptionPane.showMessageDialog(null, result);
another = JOptionPane.showConfirmDialog(null,"Test another palindrome?
");
}
while (another == JOptionPane.YES_OPTION);
}
}
5.10 IncDec
//***************************************************************
// IncDec.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 5.10
//***************************************************************
public class IncDec
{
//----------------------------------------------------------------// Creates and displays the increment / decrement GUI.
//----------------------------------------------------------------public static void main (String[] args)
{
IncDecGUI id = new IncDecGUI();
id.display();
}

}
AP-Style Multiple Choice
Solutions
1. D
2. B
3. B
4. A
5. E
6. A

AP-Style Free Response Solution


5.1
a.
implements Comparable

b.
public String getFirst()
{
return first;

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 5 Solutions


101
}
public String getLast()
{
return last;
}
public int compareTo (Object otherName)
{
if (this.last.compareTo(((Name)otherName).getLast()) == 0)
return this.first.compareTo(((Name)otherName).getFirst());
else
return this.last.compareTo(((Name)otherName).getLast());
}

c.
public String toString ()
{
return first + " " + last;
}

2007 Pearson Education

Das könnte Ihnen auch gefallen