Chapter 1. What Is Programming?


Chapter 2. Classes and Methods -- Part I


1.     Modify the Concentric program to draw a bulls eye consisting of five concentric rings of alternately red and green colors.



2.     Modify the Forecast program so that there is a call to setSize just before the first print. Experiment until you find a size that is close to the size shown in the text.



3.     Write a program to draw the International Olympic Committee logo.



4.     Write a program to draw a large circle centered in a 300 ´ 300 DrawingBox area. Then draw two equilateral triangles inscribed in that circle, forming a hexagram, sometimes known as the Star of David.

Star of David


5.     Draw a 4 ´ 4 checkerboard in a 400 ´ 400 DrawingBox area.  The squares should be colored red and black.



6.     Reproduce Figure 2.8 as closely as you can, in a 300 ´ 300 drawing box.



Chapter 3. Fundamental Data Types of Java


1.     Write a Java class called EuroShoe with a single method, convert to read a person's foot length in inches, convert it to centimeters, and print the corresponding European shoe size.



2.     Write a Java class called HeartRate with a single method, compute to read a person's age and print the range of that person's target heart rate.



3.     Nothing to show.


4.     Write and debug a program to calculate the selling price of items at a discount store where Selling price = List price - Discount + Tax.



5.     Write a program to read the three sides of a triangle and calculate its area by Heron's formula.



6.     Write a program to read the coordinates of two points and calculate the distance between them.



7.     Write a program to read four numbers, representing the number of quarters, dimes, nickels, and pennies the user possesses, and print the total number of dollars and cents.



8.     Write a program that reads a string of exactly eight characters from the user, and writes those eight characters in an output box, in three different ways:

a)     Write the even-number characters followed by the odd-numbered characters.

b)    Write all the characters in reverse.

c)     Write the first four characters in capital letters followed by the next four in lower-case.



9.     It is often important to be able to scale a picture to fit properly within a window.  Solve the previous Checkerboard problem in such a way that the size of the drawing box can be changed easily.  Allow the user to specify this size in an input box.



10.  Nothing to show.



Chapter 4. Decision Making


1.     Rewrite your application in Exercise 1 on page 93 to check that the shoe size is within the range of available sizes, 17 to 46, and to display an appropriate “error message” if not.



2.     Nothing to show.


3.     Nothing to show.


4.     The current rule (as of January 1, 2001) for Social Security contributions is this: 7.65% of your salary, up to $80,400, is taken as Social Security (FICA) tax, then 1.45% of everything above that is taken as Medicare tax. However, if you are self-employed, it is 15.3% up to $80,400, then 1.45% above that. Write a program that first asks the user whether he or she is self-employed and then asks for the annual salary, and calculates the FICA tax, the Medicare tax, and the total.



5.     At wind chill indexes of -25 and below there is danger of freezing exposed flesh; at -75 and below there is extreme danger of freezing exposed flesh. Use the wind chill formula to write an application that will print an appropriate warning.



6.     Write an application to read an integer n between 0 and 100, and write n followed by the appropriate ordinal suffix (that is, th, st,  rd, or  nd).



7.     Write a Java application to print the eligibility of a candidate for Congress.



8.     Write an application to read in a body weight (in kilograms) and calculate a weight lifter's handicap. 



9.     Write an application to read a person's gender, height, and weight, determine the body mass index, and print a message as to whether it is high or not. Your application should convert height from inches to meters and weight from pounds to kilograms.  The body mass index correlates with one's overall risk of developing heart disease. Modify your application so that it also prints a message describing the risk of heart disease.



10. Write a program that reads as input the weight, length, width, and depth of a package to be shipped by UPS, and which prints whether the package can be shipped under the restrictions given in the text. The output should indicate whether the package can be shipped at all and, if so, whether it is subject to the oversized minimum rate.



11. Write a switch statement to determine the postage rate for sending an item given the weight in ounces and the kind of mail (first class, postcard, book).



12. As part of a medical diagnosis system for a poison control center, you have to prepare the switch statement to identify proper treatment for ingestion of various substances.   The types of poison being considered are aspirin, alcohol, chloroform, rat poison, strong acid, strong alkali, strychnine, and kerosene.



13. Write an application to calculate the date following a given date. You will have to take into account leap years.



14. Write an application to read a child's weight in pounds and print the correct dosage, according to the rules given in the text, of the medication in terms of droppersful of drops, teaspoons of syrup, and tablets for that body weight. If more than one form of the medication is appropriate, give all possibilities.



15. Nothing to show.

Chapter 5. Classes and Objects II: Classes with multiple methods


1.     Modify the Hose class to report a choice of sizes in some cases, as follows: in compute, in addition to calculating y and x, calculate z as a double value equal to the value assigned to x without casting to int. Then report sizes according to the rule given in the text.



2.     Previously we presented a class to calculate social security payments. Rewrite that class to have three methods --- getData, compute, and display --- and rewrite the client accordingly.



3.     A previous exercise required that you calculate the dosage of some medicines depending upon the child's weight. Divide that class into three methods, as in the previous exercise.



4.     Nothing to show.


5.     Modify the Clock class to produce its output in text form (using the DrawingBox method drawString). Only the body of the display method should be changed.



6.     A CashRegister is an object with nine operations to add coins or bills to the cash register, namely void addPennies (int p),  addNickels (int n), and so on. These operations can also remove coins or bills when negative arguments are provided. There is also the operation int total () which returns the total amount of money in the cash register, in pennies. Write the CashRegister class.



7.     Write a Thermometer class, with three operations:  void setTemp (int t), void toggleScale(), and  void display(). The setTemp method sets the temperature to its argument (a number between 0 and 212). Initially, the temperature is interpreted on the Fahrenheit scale, but a call to toggleScale changes it to Centigrade; a subsequent call can change it back. The display method draws a thermometer in a drawing box, as a tall thin rectangle with a small circle at the bottom, with the circle and the correct portion of the rectangle in red. Show the temperature to the right of the top of the red portion of the thermometer, followed by the letter F or C, depending upon the scale. When in Fahrenheit mode, the thermometer will be assumed to show temperatures from 32 to 212; in Centigrade mode, it will show temperatures from 0 to 100. When the scale is toggled, the temperature should be recalculated so that the next time display is called it will show the correct number (although the height of the red part will not change).



8.     The Scoreboard class represents a scoreboard giving the scores in a baseball game. It gives the inning and two scores, which it displays in a DrawingBox.  The client is the class BallGame.  It should play three innings (that is, three at-bats for each side) and at the end display “Home team ahead,” “Visitors ahead,” or “Game tied.”



9.     Implement a Bowler class that will keep track of frames and a bowler's total score. We will use a simplified scoring scheme.  The client, BowlingGame, should prompt the user for several rolls and report the frame and score after each one. For now just have the bowler take six rolls, whatever the result.  You may have noticed that some input sequences are illegal. For example, if the first roll is 3, then there remain only 7 pins, so the next roll cannot be larger than 7. Modify your code to detect and complain about any illegal entries.



10. The real rules of tenpin bowling are more complicated, as given in the text.  Modify the  Bowler class to accommodate these more complicated rules.  In particular, we may need to see one or two rolls after a frame before we can score that frame.



Chapter 6. Iteration


1.     Rewrite the temperature table program to convert from Fahrenheit temperature to kelvins (absolute temperature).



2.     Write an application to print the first 20 Fibonacci numbers.



3.     There is a medieval puzzle about an old woman and a basket of eggs. On her way to market, a horseman knocks down the old woman and all the eggs are broken. The horseman will pay for the eggs, but the woman does not remember the exact number she had, only that when she took the eggs in pairs, there was one left over; similarly, there was one left over when she took them three, four, five, or six at a time. When she took them seven at a time, however, she came out even. Write an application to determine the smallest number of eggs the woman could have had.



4.     Modify the reverseDigits program from a Quick Exercise 6.5 to ignore leading zeros, so that the reversal of 12000 is 21.



5.     Consider the following process. Start with any positive integer that is not a palindrome, say 48. Add 48 to its reversal, 84; we get 48 + 84 = 132. Since 132 is not a palindrome, we add it to its reversal to get 132 + 231 = 363 and we stop, having reached a palindrome. 

a.      Write an application that reads an integer and applies the preceding process zero or more times until a palindrome results. Your application should count the number of times a number must be added to its reversal to reach a palindrome. Be sure your loop stops before an integer occurs that is too large for type int on your computer; for example, starting with 89 will require integers larger than 231 - 1 and so will be impossible on a 32-bit computer.



b.     Rewrite your program using the BigInteger class from java.math.



6.     Write an application that reads an integer and prints its prime factorization.



7.     Given an approximation to the cube root of x, we get a better approximation by computing according to the formula shown in the text.  Use this idea to write a method to calculate the cube root of x.  (Note: This method is known as Newton's method for computing cube root.)



8.     Write an application to help do payroll calculations. Your application should read wages and compute and print the State of Illinois tax due (3 percent of wages); your application should continue reading wages until an end of input is encountered. At the end of input, the application should print the total of all wages paid and the total of all Illinois state taxes due.



9.     Write a program in which a ball bounces around within a DrawingBox.



10. We were careful to set the size of the DrawingBox prior to drawing the mouse's maze in the text. Draw the mouse's maze in a size proportional to the default size of the window.




11. Write a program to draw regular polygons. When the user inputs a positive integer n in an InputBox, the program draws an n-gon in its window.



12. Suppose we wish to draw a sine curve, with x values ranging from 0 to 10 radians in increments of dx in a drawing box of width w and height h. 

a.      Write a program to draw sine curves using dots, as described in the text.



b.     Modify the program to draw sine curves using lines, as described in the text.



13. Rewrite the previous Scoreboard program to play a full 9 innings.



14. Rewrite the previous Bowler program to play a full game, and continually prompt for the next roll until the game is over.



15. Evaluate the summation expression given in the text with two different for loops.




Chapter 7. Classes and Methods III---Working with Objects


1.     Nothing interesting to show.


2.     Write a Clock client to print a daily schedule form in an OutputBox. Your program should read the starting time, the ending time, and the interval between appointment lines.



3.     Define a Complex class and write a client to exercise this class as follows: repeatedly read three numbers of type double, say x, y, and s, create and print the complex number x+iy, print its absolute value, then create and print s(x+iy). Continue until the user terminates the application.

This applet is incorporated into the larger Complex class below.


4.     Nothing interesting to show.


5.     Add three new methods to the Complex class.  public Complex add (Complex c),  public Complex multiply (Complex c), and  public Complex conjugate ().Test these new methods. Now, each input cycle needs four numbers, x, y, x’, and y’; the complex numbers x+iy and x'+iy' should be created, the three new operations should be performed on them, and the results printed.



6.     Nothing interesting to show.


7.     The class Rational contains rational numbers (that is, fractions) and has the usual arithmetic operations, as shown in the text.  Write a client where the inputs x, y, x’, and y’ represent the rational numbers x/y and x’/y’. Test plus, minus, times, and divide.



8.     Rewrite the Rational class using BigIntegers.



9.     In a Exercise 5 you represented a complex number using two real numbers: the real and imaginary parts of the complex number. The same operations as you defined in previously can be defined using polar representation, with clients seeing no change in the observable behavior of the class.



10. As another example of objects containing other objects, we can create a class that draws clocks for Chicago, New York, and Paris. It should create a DrawingBox and place the clocks in the top left, top center, and top right of the DrawingBox. Below each clock, it should display the name of the city.



11. Write a BowlingTourney program representing a competition between two bowlers.  Your client should repeatedly prompt for the bowler name and pin count and announce a winner when both games are over.



12. Nothing interesting to show.


13. Nothing interesting to show.


14. Write a simple drawing program by repeatedly prompting the user to draw and adjust a new figure (triangle or circle) and by drawing these in the same drawing box.



Chapter 8. One-Dimensional Arrays


1.     Nothing interesting to show.


2.     Make the following changes in the GradeBook program.


a.      Use an array for the grades.

b.     Adapt the methods to an array of grades.

c.     Add the ability to determine how many grades to read for each student.

d.     Add two more exam grades for each student, and drop the lowest in computing the average.



3.     Nothing interesting to show.


4.     Nothing interesting to show


5.     A serious problem with our final histogram output is that it has no labels. Each bar should have a label underneath it giving the range of scores that it includes. Raise the bar graph and place the labels under each bar. You may assume that the bars are wide enough for the labels to fit underneath.



6.     Nothing interesting to show.


7.     You should run these modified programs yourself to determine the effects.


8.     Nothing interesting to show.


9.     The sieve of Eratosthenes is a method of finding prime numbers by sifting out composite numbers. Write an application to compute the prime numbers less than N (a symbolic constant) by the sieve of Eratosthenes.



10. Write a self-reproducing Java program. That is, the program should print an exact copy of itself (P. Bratley and J. Millo, “Self-Reproducing Programs,” Software---Practice and Experience 2 (1972), pp. 397 -- 400).



11. The most important feature of spreadsheet programs like is that the value contained in one cell can be computed as a function of the values in other cells. If cell A1 contains the wholesale cost of a product, and A2 its retail cost, then you can enter the formula A2-A1, representing the profit on that item, into cell A3. It will be computed automatically when you enter the formula, and recalculated automatically whenever the contents of A1 or A2 change. One issue that arises in writing a spreadsheet program is what to do if there is a circular dependency among the items in the spreadsheet. Such a mistake must be detected, so that the user can be warned, but how? We simplify the problem by having only a single row of cells instead of the usual grid of cells and, more important, by allowing each cell to depend on at most one other cell.


Your program should have as its input a sequence of n numbers (terminated by end of input) in the range -1, …, n-1, giving the contents of the array cells. If cells[i] contains  j>=0, it means that cell i is a function of cell  j; if  cells[i] contains -1, it means that cell  i does not depend on any other cell. The dependencies illustrated in the text would be given as the 10 numbers -1 0 1 6 7 4 5 -1 -1 7.  If there is a cycle, print a message indicating that cell k is in a cycle; otherwise, print a message indicating that there are no cycles.



12. Write a program that animates the findMax function (defined in the text). It should start by generating an array of 20 random numbers between zero and one (use Math.random()).  Draw the array as a row of bars of varying height. At each iteration, the bar at maxloc should be colored in red (, while the bar at i should be gray (Color.gray). Show the array after each iteration of the loop, pausing for a brief interval after each iteration.


13. Revise the solution to Exercise 14 of Chapter 7 to use an array of triangles and circles.  When a new shape is added and adjusted, erase and redraw all the shapes.



14. Extend the previous exercise to allow the user to specify the shape to change.  Also give the option of removing a shape.




Chapter 9.  Nested Loops and Two-Dimensional Arrays


1.     To assist a young friend learning to multiply, write an application to print a multiplication table.



2.     Write a Boolean-valued method whose argument is an integer array that returns true if the array is symmetrical and false if not.



3.     Write a method whose argument is a square matrix and which computes and returns its transpose.  Print both the original array and its transpose.

See next exercise.


4.     In Exercise 3, instead of placing the transpose into a separate array, calculate the transpose in place; that is, change the argument to its transpose by rearranging its elements.



5.     Write an application to print Pascal's triangle.



6.     Numerous representations of the crossword puzzle are possible.  Change the representation we used in two different ways:


a.      First, leaving theBoard as it is, use a different representation for theNumbers:  Instead of a parallel two-dimensional array, use an n ´ 2 integer array, where n is the number of numbered squares.  Row i of this array gives the row and column number in the puzzle of the square numbered i.



b.     Now change the representation for the entire puzzle to be a single two-dimensional array of Square objects.  Each Square object contains its contents (as a character) and its number (if any).



7.     This exercise is misplaced, since it requires the Date class from Chapter 10.  It is presented again in Chapter 10.


8.     Define two matrix addition operations:


void addMatrices (double[][] A, double[][] B, double[][] C)

double[][] addMatrices (double[][] A, double[][] B)


The first method adds A and B and places the result in C. The second allocates the result matrix in the heap and returns a reference to it.  Define two versions of multMatrices for multiplying two matrices, analogous to the two versions of addMatrices.



9.     A magic square is an n ´  n grid of the integers 1 through n^2 that sum to the same value across rows, down columns, and along the two diagonals. Write an application to read an odd integer and display a magic square of that order. (The Mathematical Intelligencer, Vol. 14, No. 3, 1992, pp. 15--16.)



10. Conway's Game of Life is a simulation of a cellular automaton from one generation to the next.  It is played out on a two-dimensional array of "cells" according to rules given in the text.  Write an application that plays out Conway's Game of Life on an 80 ´  80 board, using * for a filled cell and "blank" for an empty cell. You should keep two copies of the array---one for the present generation and one for the succeeding generation.  Try various initial patterns.  (Conway's Game of Life was popularized by Martin Gardner's mathematical games column in the October 1970 and February 1971 issues of Scientific American. Also see William Poundstone, The Recursive Universe [Oxford: Oxford University Press, 1987].)



11. The American Bankers' Association font E-13B is used to print numbers on checks in magnetically readable ink. It is a simple font employing a 7 ´  7 grid.  Write two methods:


void printE13B (int digit) prints digit (an integer between 0 and 9), using Xs for the filled-in boxes and leaving the others blank.


int readE13B (boolean[][] grid) has as its argument a 7 ´  7 array of Booleans purporting to contain a character in the E-13B font, in the obvious way. The readE13B returns the corresponding digit, or -1 if grid contain none of the E-13B characters.  To solve this problem, employ a 10 ´  7 ´  7 three-dimensional array.



12. Add operations drawBox and drawDisk to the SoftFrame class. These calls draw filled shapes. The method drawBox is given two corners of a rectangle and draws the rectangle with the interior filled in in black. The method drawDisk has the same arguments as drawCircle, but it draws a circle filled in in black.

See the next exercise.


13. Use the line-drawing operations of the SoftFrame class and the drawBox method defined in the previous exercise to draw a checkerboard.



14. Program Bresenham's circle-drawing algorithm and compare its performance to that of drawCircle.



15. There’s no change in behavior over previous versions.

Chapter 10.  Classes and Methods IV: Static Methods and Variables


1.     There’s no change in behavior over previous versions.


2.     Nothing interesting to show.


3.     Given the time of day in terms of the variables hour, minute, second, and dayHalf (that is, AM or PM), write a class method called fractionOfDay to calculate and return the fraction of the day (type double) that has elapsed.



4.     Write a static method triangle that takes three double values and returns true if the three values are the sides of a triangle and false if not.



5.     Write a static method called majority having three Boolean parameters. The value returned should be true if any two of the arguments are true and false otherwise.



6.     Nothing interesting to show.


7.     Nothing interesting to show.


8.     Nothing interesting to show.


9.     Fourteen different year calendars are possible---seven for January 1 falling on each day of the week in a nonleap year and seven more for a leap year. 


a.      Print the 14 different calendars.



b.     Write an application to print a table indicating which of the 14 different calendars to use for each year from 1900 to 1999.



10. Write a method to return the number of days left in a year. The arguments to the method should be the month, day, and year.



11. Nothing interesting to show.


12. Write a method that returns the season, given the month and day. 



13. Daylight savings time moves the clock ahead one hour in the spring and back one hour in the fall.  As of 1987, daylight savings time begins on the first Sunday in April and ends on the last Sunday in October.  Write a method daysOfDaylightSavings that computes the number of days of daylight savings time in a given year, which is a parameter of the method.



14. Nothing interesting to show.


15. Write a class JulianDate that implements everything our Date class does, except that it uses the Julian calendar.  Include in the JulianDate class constructor JulianDate (Date gd) that takes a Gregorian data as an argument, and constructs its Julian equivalent.



16. Nothing interesting to show.


Chapter 11.  The Java AWT Part I---Mouse Events (Optional)


1.     The beauty of having Eyes as a separate class is that it is easy to create new eyes and different kinds of eyes.


a.      Add eyes in the other two corners of the application window.



b.     Modif y the application so that the eyes change only when the mouse is clicked.



c.     Define a class ShyEyes that is like Eyes except that its pupils always turn away from the cursor. Define your application to contain both Eyes and ShyEyes.



d.     Modify the Eyes application so that the eyes "sleep" when the mouse is outside the application, and "awaken" when it moves inside the application.  You can draw a sleeping eye by drawing a horizontal diameter instead of the pupil.



e.      Modify the Eyes application further so that when the cursor is inside the application area, the eyes sleep when you press on the mouse button, and awaken when you release.



2.     Write a method


void drawPolygon (DrawingBox d, Point[] points)


that connects all the points in an array of points by lines (including connecting the last point to the first). To test it, write a program in which the users designates the vertices of the polygon by mouse clicks; each time the mouse is clicked, the polygon is redrawn with the new point included as the last point.



3.     Program Conway's Game of Life as a graphical application.  Consider the top row to be adjacent to the bottom row (as if the game board were rolled over to form a cylinder), and the left column adjacent to the right column (as if the cylinder were rolled around to form a donut). Permit the selection of an initial pattern by clicking with the mouse. Code your mouse listener so that the game begins when the user clicks on a designated area of the DrawingBox (such as near the edge, or in a "start button" that disappears once the game begins).



4.     Write a tic-tac-toe playing application. You click with the mouse in a square to make a move, alternating between "X" and "O." The game should continue like this until X or O wins or all spaces are filled, at which time an appropriate message should be displayed, written across the playing board.



5.     Modify the mouse maze-walking program from Chapter 9 so that the MouseMazeClient is a MouseListener.  The client should make a move every time the mouse is clicked in the DrawingBox.



6.     In computerized drawing programs, one places a shape on the screen and then can perform various operations, such as moving, resizing, and rotating. Define the Rectangle class to represent rectangles and perform those operations.  Write an application to test this class. It should start with a square drawn in the middle of the application's window. There should be buttons indicating whether to move, reshape, or rotate; checkboxes indicating which corner to move in a reshape action; and text fields to indicate the distance and direction to move the entire rectangle or the selected corner.



7.     Write an application similar to the one in Exercise 6, but using the mouse to indicate how to move or reshape the rectangle. This application should have just one button, the rotate button, and it should start, as before, with a square drawn in the middle of the window. The square is rotated by pressing the rotate button, and it is moved or resized by giving two mouse clicks, as follows. Assume the mouse clicks are at points p and q, respectively. If p is "near" one of the rectangle's corners, then this is a reshape operation, and q is the new location of that corner. Otherwise, if p is "near" one of the rectangle's sides, then this is also a reshape operation, but one that moves that entire line, either vertically or horizontally. If the line is a horizontal line, then q's y-coordinate is the y-coordinate to which that line should be moved; if it is a vertical line, q's x-coordinate gives the x-coordinate. If p is not near a corner or a line but is inside the rectangle, then this is a move operation: q gives the location to which the rectangle should be moved; specifically, the rectangle should be moved so that q is in the same relative location with respect to the rectangle as p was before the move. Finally, if p is outside the rectangle, the mouse clicks should be ignored. 



8.     A somewhat more difficult version of Exercise 7 is to use "clicking and dragging" to effect the moves and reshapes. That is, to move a corner of the rectangle, you should click and hold the mouse key, move the mouse to the desired new location of the corner, and release it. This should work similarly for reshaping on a side and for moving. Furthermore, you should show the rectangle changing shape and moving as the mouse is dragged.



Chapter 12.  Inheritance and Exceptions


1.     All of the programs should still behave as they did before.


2.     Add an instance method to the Mouse class---public void makeRecordMove()---which simply invokes the method makeMove() and then records the new location and direction for the mouse. Use a large array to record the configurations for the mouse. The client of Mouse (namely, MouseController) should be changed to invoke the instance method makeRecordMove() instead of makeMove(). When the mouse has completed its navigation, the client should print a summary of the mouse's moves.



3.     Now that the base Mouse class can monitor its subclasses (acting like a good “parent” to its “children”), we can allow the superclass to intervene when something bad happens. That is, you should modify makeRecordMove so that it can prevent the mouse from running in circles. First, define a new protected method, void backup(). Now, when makeMove() returns to makeRecordMove() with a new configuration with a location that the mouse has already experienced, makeRecordMove() should refuse that suggestion and invoke another method---makeAlternativeMove(int attempt)---which will choose a different move. The makeRecordMove() similarly may reject that suggestion and ask makeAlternativeMove(int attempt) for another. If, after three tries, makeAlternativeMove(int attempt) is unable to find a suitable move, then makeRecordMove() should cause the mouse to back up.  (Note.  To prevent the mouse from exiting through the entrance, we put a wall across the entrance as well. 



Chapter 13.  Java AWT --- Part II (optional)


1.     Modify the Temperature program so that it gets a temperature in degrees Fahrenheit and displays the equivalent Centigrade and Kelvin temperatures.



2.     In Section 3.5 on page 86, you wrote a program to calculate the price of a coffee order. Turn this application into a graphical program with appropriately labeled text fields for input. 



3.     Reprogram the BodyMass program so that the message "This is not considered high" is displayed in blue, 16-point Helvetica type, while the message "This is considered high" is displayed in red, 40-point bold Helvetica type. Be sure to resize the window when increasing this message size.



4.     Modify our CalendarApplet so that today's date has a pink background.

See the following exercise.


5.     Modify our CalendarApplet so that the first row of the calendar body ("Sun Mon ... Sat") is displayed in magenta, bold, 16 point Helvetica font.



6.     Write a program with a text field for input of a number between 0 and 9, which draws the seven-segment version of that number.



7.     In Exercise 7 on page 141 you wrote an application to compute whether a person is eligible for candidacy for Congress, given the person's age and years of citizenship. Rewrite this as a graphical program, using two TextFields for input.



8.     In Exercise 11 on page 144 you wrote a switch statement to compute the postage rate for an item, given the weight of the item and the mail class. Write a graphical program to compute and display the postage rate. Use a TextField to input the weight, and use three grouped radio buttons to select the class of mail.



9.     Write a program to display various red, green, and blue (RGB) combinations.  Write a program that reads three values, each between 0 and 255, representing the red, green, and blue components, and displays a filled rectangle in that color.  Use text fields for input.  Include six buttons, labeled Less red, Less green, and so on.  When one of these buttons is pushed, the value in the corresponding TextField is incremented or decremented by 10, and the new color is displayed.



10. Define a program ColorTest that has buttons for changing the three color hues (red, green, and blue) by a fixed amount, and for changing the brightness. Another button, labeled “increase” or “decrease” indicates in which direction the other buttons operate; clicking on it toggles it. The program should display boxes showing the red, green, and blue components and the combined color, side by side; each time one of the buttons is pressed, these colors need to be changed.



11. Write a program to display a color bar. You should have two checkboxes, labeled “Color 1” and “Color 2” respectively, and three text fields, labeled “Red”, “Green”, and “Blue”. The user enters two colors by first clicking on the Color 1 box and then entering integers (in the range 0 to 255) in the text fields, and then clicking on the Color 2 box and entering integers in the text fields. Given these two colors, show a bar of colors consisting of 10 narrow strips of color, with the leftmost strip containing color 1 and the rightmost strip containing color 2, and the eight strips in between containing shades between those two colors.



12. In Exercise 12 in Chapter 6, you wrote an application to draw a sine curve in a drawing box.  Modify this application in three ways:

a.      Add two text fields to replace the input windows prompting for the x range and the x increment.  Each time a new number is entered and the user types the enter key, the graph should be redrawn.

See the following solution.

b.     Add a check box from which the user can choose a sine, cosine, or tangent curve.  If more than one curve is selected, draw all the curves at once.  If one of the number inputs is changed, all the selected curves should be redrawn.


c.     Revise the program from part b to use radio buttons instead of check boxes, so that only one curve at a time can be selected.



13. Modify the RandomCircles program from Section 13.5 on page 502 to draw circles filled with a specified color.


Chapter 14.  Recursion


1.     Nothing to show.


2.     An example of the elegance of recursive definitions comes from a problem in everyday life:  making change. 

a.      Develop a recursive definition for the number of ways to make change for n dollars, assuming that pennies, nickels, dimes, quarters, half dollars, dollar bills, and five-dollar bills are available. 

See the following solution.

b.     Use your definition as the basis of a program to compute the number of ways to make change for a specified amount.


c.     Modify your program in part (b) to list all the ways of making change instead of just computing the number of ways.



3.     Suppose that you are in charge of a softball league with 16 teams. During the 15-week season, each team must play each other team exactly once.  Write a recursive application that will print an appropriate 15-week schedule.



4.     Write a program to compute Ackermann's function.  Be warned that the value of A(m, n) grows super-rapidly!



5.     One of the most famous of all recursive definitions is that of the Fibonacci function.  Implemented directly, it is extremely slow.  A simple cache, consisting of an array of n integers, can speed it up tremendously.  Implement the Fibonacci function directly and using a cache, and compare the speeds of the two implementations



6.     Write a Java method to calculate the nth number in the Newman-Conway sequence defined by P(1) = P(2) = 1, and, for n ³ 3, P(n) = P(P(n-1))+P(n-P(n-1)).



7.     Nothing reasonable to show.


8.     Nothing interesting to show.


9.     Nothing interesting to show.


10. Nothing interesting to show.


11. Nothing interesting to show.


12. Nothing interesting to show.


13. Nothing interesting to show.


14. Use removeNthM to solve the "Josephus problem," named for the Jewish historian of the Roman-Jewish War of the first century. The story goes that 10 Jews were trapped in a cave by Roman soldiers and they determined to commit suicide rather than surrender. They decided to do so in an unusual way: they all stood in a circle, and, with one man chosen to begin, every other man committed suicide. The question is, Which was the last man to die?  We want you to solve this problem in a more general setting.  For given positive integers m and n, construct a list of the numbers from 1 to n. Then, starting from 1, remove every mth item; if this takes you past the end of the list, then consider the list to be a circle and continue from the beginning.



15. Suppose you fold a piece of paper in half, then fold it in half again, and so on for some number of folds. (The folds are parallel to one another.) If you unfold and flatten the paper, the pattern of folds will be Ú after one fold, ÙÚÚ  after two folds, ÙÙÚÚÙÚÚ after three folds, and so on (try it!).  The pattern for n+1 folds is obtained from the pattern for n folds as follows. Take the reflected pattern for n folds, add the fold Ú at the end, and then add the original pattern for n folds.  Reflected means upside down and in reverse order. (Again, try it!) Using 1 for Ú and 0 for Ù, write a recursive method to produce the pattern for n.



16. Nothing interesting to show.


17. Write a program to draw members of the sequence of curves called the Sierpinski gasket; see "Four Encounters with Sierpinski's Gasket," by Ian Stewart, The Mathematical Intelligencer 17, no. 1 (January 1995), pages 52--64, for details.



Chapter 15.  Text Processing and File Input/Output


Note.  Since all of these programs involve reading and/or writing to the local file system, they cannot be run as applets without altering the security settings for your computer.  Therefore, we have provided the class files that you can download and run as applications.


1.     Write a program to read characters from a file (up to end of file) and calculate the number of characters that the file contains. 

CharCount.class CharCountClient.class


2.     Extend the program you wrote for Exercise 1 so that it also counts the number of lines that the file contains.  Do this by counting the number of newline characters that the file contains.

LineCount.class LineCountClient.class


3.     Extend the program you wrote for Exercise 2 so that it also counts the number of words that the file contains.  For simplicity, you may assume that a word is a sequence of non-blank characters, where a blank character is a space, newline, or tab.

WordCount.class WordCountClient.class



4.     Write a program to print this year's calendar to a file.  (Refer to Exercise 9 in Chapter 10.)

Date.class PrintCalendar.class PrintCalendarClient.class


5.     Modify the Cat class so that if it catches a FileNotFoundException, instead of stopping, it asks the user to type a new file name using an InputBox.

Cat.class CatClient.class


6.     Modify Exercise 5 so that if yet another FileNotFoundException occurs, the program repeatedly asks the user to type a new file name.  If the user enters an empty string, then the program should terminate.

Cat.class CatClient.class


7.     Write a program, called Find that reads a file, and prints all lines that contain some word.

Find.class FindClient.class


8.     Write a program, called Crypt that reads a file, and produces a new file that is a Caesar Cipher of the original.

Crypt.class CryptService.class


9.     Word-processing programs ignore multiple spaces and line breaks in the user's input and simply place as many words on each line as possible, with one space between each pair of words. Write a program to do this line filling. If a word is too big to fit on one line, break it into as many lines as necessary.

LongLines.class LongLinesClient.class


10. Extend your program from Exercise 9 to fill lines to the width of the column. Spaces should be added between words as evenly as possible.

Justify.class JustifyClient.class


11. The format of the input to our mail-merge application is flawed in two ways:

a.      The character % cannot appear in the letter and # cannot appear in any of the fields.

b.     Because no special character separates one set of fields from the next, the accidental omission of one field would throw off the entire set of letters.

Rectify the first problem by allowing # and % to be "escaped" in the input; that is, if the characters \# appear in the input, # appears in the output, and similarly for \%. The character \ itself must be escaped in the same way. Rectify the second problem by using % instead of # to separate fields within a single group (that is, to separate the fields for a single customization of the letter) and # to separate groups. Be sure to test your application on an input that has missing fields.

MailMerge.class MailMergeClient.class


Chapter 16.  Case Study: The Game of Reversi


1.     This exercise does not cause a change in behavior.


2.     This exercise does not cause a change in behavior.


3.     This exercise does not cause a change in behavior.


4.     Add to the Reversi program a button that will allow the Person to undo his or her most recent move (and of course undo Reversi's move that was made in response to the Person's most recent move).



5.     Add to the Reversi program a button that can be clicked when it is the Person's turn, that will ask Reversi to show what the possible moves are.  Indicate the possible moves by coloring the relevant squares blue.

See the solution to the following exercise.


6.     Further indicate the "best" move by determining which move the SmartPlayer would make, and color its square red.



7.     The SmartPlayer isn't really so smart! Simply counting the number of stones flipped is rather shortsighted. It doesn't take into account strategies like trying to occupy the edge squares or the corner squares. Program a SmarterPlayer class that evaluates a board by computing a weighted count of the stones: count +24 for a corner square, +5 for an edge square, and +1 for other squares.



  1. (Advanced:  Requires Recursion)  Again, the SmarterPlayer isn't so clever! A much stronger playing strategy involves looking ahead more than one move. Each move that a player looks ahead is called a ply. For example, an ExpertPlayer might utilize a two-ply look-ahead.  The evaluation of a move is determined by the situation that will exist after that move and after the opponent makes a move in response. Three-ply and four-ply look-aheads carry this idea even further!  In general, an n-ply look-ahead involves building a game tree, with the present board leading to several successor boards (one for each possible move), and each of those boards leading to several successors, and so on.  At the bottom of such a game tree, each board is evaluated using a static stone-counting scheme such as that used by the SmarterPlayer in Exercise 6. At the level above those terminal boards, the opponent will presumably select its best move by choosing the minimum value of the boards below. At the level above that, the ExpertPlayer selects the maximum, and so forth. This is the strategy if the look-ahead is an even number.  If it is an odd number, then the ExpertPlayer selects from bottommost boards, and the role of minimizing and maximizing is reversed.  For obvious reasons, this technique is called a min-max game-playing strategy.  Program such an ExpertPlayer.