Beruflich Dokumente
Kultur Dokumente
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
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
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.
S 78
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
S 80
//
// 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
// 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
public
{
int
int
int
int
S 83
S 84
S 85
=
=
=
=
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
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
//***************************************************************
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
S 89
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());
}
}
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
//***************************************************************
// 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
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());
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
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
private
private
private
private
private
S 93
S 94
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;
S 96
}
//----------------------------------------------------------------// 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
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
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
{
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
b.
public String getFirst()
{
return first;
c.
public String toString ()
{
return first + " " + last;
}