




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































2 Chapter 1. Java Primer
R-1.6) Hint The easy thing to do is to write a loop. R-1.6) Solution
public int sumOdd(int n) { int total = 0; for (int j=1; j <= n; j += 2) total += j; return total; }
R-1.7) Hint The easy thing to do is to write a loop. R-1.7) Solution
public int sumSquares(int n) { int total = 0; for (int j=1; j <= n; j++) total += j∗j; return total; }
R-1.8) Hint You might use a switch statement. R-1.8) Solution
public int numVowels(String text) { int total = 0; for (int j=0; j < text.length( ); j++) { switch (text.charAt(j)) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': total += 1; } } return total; }
R-1.9) Hint Consider each character one at a time.
R-1.10) Hint Consider using get and set methods for accessing and mod- ifying the values. R-1.11) Hint The traditional way to do this is to use setFoo methods, where Foo is the value to be modified. R-1.11) Solution
public void setLimit(int lim) { limit = lim; }
R-1.12) Hint Use a conditional statement. R-1.12) Solution
public void makePayment(double amount) { if (amount > 0) balance −= amount; }
R-1.13) Hint Try to make wallet[1] go over its limit. R-1.13) Solution
for (int val=1; val <= 58; val++) { wallet[0].charge(3∗val); wallet[1].charge(2∗val); wallet[2].charge(val); }
This change will cause wallet[1] to attempt to go over its limit.
C-1.14) Hint The Java method does not need to be passed the value of n as an argument. C-1.15) Hint Note that the Java program has a lot more syntax require- ments. C-1.16) Hint Create an enum type of all operators, including =, and use an array of these types in a switch statement nested inside for-loops to try all possibilities. C-1.17) Hint Note that at least one of the numbers in the pair must be even. C-1.17) Solution
hold solutions. If this still seems to hard, then consider using six nested loops (but avoid repeating characters and make sure you allow all string lengths).
C-1.22) Solution Here is a possible solution:
public static void permute(ArrayList bag, ArrayList permutation) { // When the bag is empty, a full permutation exists if (bag.isEmpty( ) ) { System.out.println(permutation); } else { // For each element left in the bag for(int i = 0; i < bag.size( ); i++) { // Take the element out of the bag // and put it at the end of the permutation Object obj = bag.get(i); bag.remove(i); permutation.add(obj);
// Permute the rest of the bag (recursively) permute(bag, permutation);
// Take the element off the permutation // and put it back in the bag permutation.remove(permutation.size( ) − 1); bag.add(i, obj); } } }
public static void main(String[ ] args) { ArrayList orig = new ArrayList<>( ); char[ ] word = {'c', 'a', 't', 'd', 'o', 'g'}; for (char c : word) orig.add(c); permute(orig, new ArrayList( )); }
C-1.23) Hint Go back to the definition of dot product and write a for loop that matches it.
C-1.23) Solution
6 Chapter 1. Java Primer
public int[ ] compute(int[ ] a, int[ ] b) { if (a.length != b.length) throw new IllegalArgumentException("arrays must have same length") int[ ] c = new int[a.length]; for (int j=0; j < a.length; j++) c[j] = a[j] ∗ b[j]; return c; }
C-1.24) Hint The card is no longer needed as an explicit parameter. C-1.24) Solution
public void printSummary( ) { System.out.println("Customer = " + customer); System.out.println("Bank = " + bank); System.out.println("Account = " + account); System.out.println("Balance = " + balance); System.out.println("Limit = " + limit); }
C-1.25) Hint You might use a StringBuilder to compose the pieces of the string into one large string (including newlines). C-1.25) Solution
public String toString( ) { StringBuilder sb = new StringBuilder( ); sb.append("Customer = " + customer + System.lineSeparator( )); sb.append("Bank = " + bank + System.lineSeparator( )); sb.append("Account = " + account + System.lineSeparator( )); sb.append("Balance = " + balance + System.lineSeparator( )); sb.append("Limit = " + limit + System.lineSeparator( )); return sb.toString( ); }
P-1.26) Hint Use an array to buffer all the original lines. P-1.27) Hint You do not need to use a graphical user interface, but you may want to use the System.console() method. P-1.28) Hint Define a way of indexing all the sentences and the location in each one and then work out a way of picking eight of these locations for a typo.
R-2.1) Hint Think of applications that could cause a death if a computer failed. R-2.1) Solution Air traffic control software, computer integrated surgery applications, and flight navigation systems. R-2.2) Hint Consider an application that is expected to change over time, because of changing economics, politics, or technology. R-2.3) Hint Consider the File or Window menus. R-2.4) Hint You can make the change and test the code. R-2.4) Solution The problem is that when a $5 penalty is assessed, pre- sumably because of an attempt to go over the credit limit, the call charge(5) recursively invokes the PredatoryCreditCard.charge method; since that fee could again be an attempt at violating the credit limit, it too may fail, leading to an infinite recursion. R-2.5) Hint You can make the change and test the code. R-2.5) Solution The goal is to assess a $5 charge as a penalty, yet that charge may be refused by the call to super.charge(5) if the user is already at or near the credit limit. R-2.6) Hint Your program should output 42, which Douglas Adams con- siders to be the answer to the ultimate question of life, universe, and ev- erything. R-2.6) Solution public static void main(String[ ] args) { FibonacciProgression fp = new FibonacciProgression(2,2); for (int j=0; j < 7; j++) fp.nextValue( ); // ignore the first 7 values System.out.println(fp.nextValue( )); }
R-2.7) Hint A long value can be no larger than 2^63 − 1.
R-2.7) Solution 256 calls to nextValue will end on the value 2^63. Since the maximum positive value of a long is 2^63 − 1, 2^56 − 1 calls to nextValue can be made before a long-integer overflow.
R-2.8) Hint Code up an example and see what the compiler says.
R-2.9) Hint Think about what happens when a new instance of class Z is created and when methods of class Z are called.
R-2.9) Solution There are two immediate inefficiencies: (1) the chaining of constructors implies a potentially long set of method calls any time an instance of a deep class, Z, is created, and (2) the dynamic dispatch algorithm for determining which version of a certain method to use could end up looking through a large number of classes before it finds the right one to use.
R-2.10) Hint Think about code reuse.
R-2.10) Solution Whenever a large number of classes all extend from a single class, it is likely that you are missing out on potential code reuse from similar methods in different classes. There is likely some factoring of methods into common classes that could be done in this case, which would save programmer time and maintenance time, by eliminating duplicated code.
R-2.11) Hint Review the section about casting in an inheritance hierarchy, and recall that an object behaves according to what it actually is, not what it is called.
R-2.11) Solution Read it. Ship it. Buy it. Read it. Box it. Read it.
R-2.12) Hint Review the definition of inheritance diagram, and begin your drawing with Object as the highest box.
R-2.13) Hint Casting in an inheritance relationship can only move up or down the hierarchy.
R-2.13) Solution No, d is referring to a Equestrian object that is not not also of type Racer. Casting in an inheritance relationship can only move up or down the hierarchy, not “sideways.”
R-2.14) Hint You don’t need to declare the array, just show how to use an exception try-catch block to reference it.
private int chargesThisMonth = 0; // new instance variable
public void processMonth( ) { chargesThisMonth = 0; // reset ... }
public boolean charge(double price) { boolean isSuccess = super.charge(price); // call inherited method if (!isSuccess) balance += 5; // assess a $5 penalty chargesThisMonth++; if (chargesThisMonth > 10) balance += 1; // assess a $1 fee return isSuccess; }
C-2.19) Hint Keep track of how much has been paid during the current month.
C-2.20) Hint Don’t forget you can use getBalance( ) as well.
C-2.20) Solution
public void processMonth( ) { if (getBalance( ) > 0) { double monthlyFactor = Math.pow(1 + apr, 1.0/12); setBalance(monthlyFactor ∗ getBalance( )); } }
C-2.21) Hint You need to use the super keyword in B and C.
C-2.21) Solution
12 Chapter 2. Object-Oriented Design
public class A { int x = 1; public void setIt(int y) { x = y; } public int getIt( ) { return x; } }
public class B extends A { int x = 2; public void setIt (int y) { x = y; } public int getIt( ) { return x; } public void superSetIt (int y) { super.x = y; } public int superGetIt( ) { return super.x; } }
public class C extends B { int x = 3; public void setIt (int y) { x = y; } public int getIt( ) { return x; } public void superSetIt (int y) { super.x = y; } public int superGetIt( ) { return super.x; } public void superDuperSetIt(int y) { super.superSetIt(y); } public int superDuperGetIt( ) { return super.superGetIt( ); } public static void main(String[ ] args) { C c = new C( ); System.out.println("C's is " + c.getIt( )); System.out.println("B's is " + c.superGetIt( )); System.out.println("A's is " + c.superDuperGetIt( )); c.superDuperSetIt(4); System.out.println("C's is " + c.getIt( )); System.out.println("B's is " + c.superGetIt( )); System.out.println("A's is " + c.superDuperGetIt( )); } } C-2.22) Hint Recall the rule about inheritance in Java. C-2.22) Solution Inheritance in Java allows specialized classes to be built from generic classes. Because of this progression from generic to special- ized in the class hierarchy, there can never be a circular pattern of inheri- tance. In other words, there cannot be a superclass A and derived classes B and C such that B extends A , then C extends B , and finally A extends C. Such a cycle is impossible because A is the generic superclass from which C is eventually extended, thus it is impossible from A to extend C ,
14 Chapter 2. Object-Oriented Design
P-2.30) Hint You don’t have to use GUI constructs; simple text output is sufficient, say, using X’s to indicate the values to print for each bar (and printing them sideways). P-2.31) Hint When a fish dies, set its array cell back to null. P-2.32) Hint Use random number generation for the strength field. P-2.33) Hint Create a separate class for each major behavior. Find the available books on the Internet, but be sure they have expired copyrights. P-2.34) Hint Lookup the formulas for area and perimeter on the Internet. P-2.35) Hint You need some way of telling when you have seen the same word you have before. Feel free to just search through your array of words to do this here. P-2.36) Hint While not always optimal, you can design your algorithm so that it always returns the largest coin possible until the value of the change is met.
R-3.1) Hint Use a calculator to aid in the arithmetic.
R-3.2) Hint You have to have your random number select a random index in the array, so be sure to keep track of the number, n , of entries in the array and do not index past index n − 1.
R-3.3) Hint The alphabets for most alphabet-based languages are included in the Unicode character encoding standard. R-3.3) Solution The alpha array and the various uses of value 26 would have be changed to the new alphabet and its size. In addition, all the places that use the literal A to refer to the first letter would now have to be changed to the first letter in the new alphabet. In this case, it would be better to define a final static int FIRSTLETTER, set it to the first letter, and use it instead of A. This assumes the messages are still in upper-case, of course.
R-3.4) Hint You may want to add a new instance variable to track if the game has been completed.
R-3.5) Hint Make the modification in the code and test it. R-3.5) Solution There are no negative consequences if removing those lines (in fact there would be an every so slight increase in efficiency with- out). While the internal state may seem inconsistent with tail referencing a defunct node, that tail reference is never accessed for an empty list, so the inconsistency has no effect.
R-3.6) Hint It is okay to have an algorithm running in linear time. R-3.6) Solution
R-3.10) Solution
public int size( ) { if (tail == null) return 0; Node walk = tail−>next; int count=1; while (walk != tail) { count++; walk = walk.getNext( ); } return count; }
R-3.11) Hint Do not include the sentinels in the count.
R-3.11) Solution
public int size( ) { int count=0; Node walk = header−>next; while (walk != trailer) { count++; walk = walk.getNext( ); } return count; }
R-3.12) Hint Carefully relink existing nodes.
R-3.13) Hint Recall that a two-dimensional array in Java is really a one- dimensional array such that each entry is itself a reference to a one-dimensional array.
R-3.14) Hint Recall the ways for doing array copying in the java.util.Arrays class.
R-3.14) Solution It seems a stretch to come up with three meaningful ways, but technically each of the following will suffice:
backup = original.clone( );
backup = java.util.Arrays.copyOf(original, backup.length);
backup = java.util.Arrays.copyOfRange(original, 0, backup.length);
R-3.15) Hint You can rely on the size variable to walk the correct number of steps when traversing the lists.
R-3.16) Hint The sentinels are irrelevant to the equivalence of two lists.
18 Chapter 3. Fundamental Data Structures
C-3.17) Hint You don’t need to sort A. C-3.17) Solution
public int missing(int[ ] A) { boolean[ ] found = new boolean[A.length]; // false, by default for (int val : A) found[val] = true; for (int k=1; k < found.length; k++) if (!found[k]) return k; return −1; // shouldn't happen if input as expected }
C-3.18) Hint It might help to sort B. C-3.18) Solution Sort the array B then scan it from front to end looking for the repeated entries. Each pair of repeated integers will be consecutive in the sorted listing. C-3.19) Hint Add items at the “end” of the contiguous run of objects in the array. For removing an object, consider first swapping it with the object at index n − 1. C-3.19) Solution
public void add(GameEntry e) { if (numEntries < board.length) { board[numEntries] = e; numEntries++; } // otherwise no room for new entry }
public GameEntry remove(int i) throws IndexOutOfBoundsException { if (i < 0 | | i >= numEntries) throw new IndexOutOfBoundsException("Invalid index: `` + i); GameEntry temp = board[i]; if (i != numEntries - 1) board[i] = board[numEntries - 1]; board[numEntries-1] = null; numEntries--; return temp; }
C-3.20) Hint Imagine what would happen if a = 1.