Chapter 1 -- What Is Programming?

    Exercises--First Set

    Chapter 2 -- Basic Elements of Java

    Exercises--First Set

    Exercises--Second Set

    Chapter 3 -- Applets

    Exercises--First Set

    1. Modify TempApplet so that it gets a temperature in degrees Fahrenheit and displays the equivalent Centigrade and Kelvin temperatures.
     Fahrenheit to Centigrade and Kelvin Applet

    2. Write the Thermometer applet, which reads a temperature in degrees Fahrenheit and draws a thermometer with the correct number of degrees filled in. You should draw the thermometer's shape as a tall thin rectangle with a small circle at the bottom, with the circle and the correct proportion of the rectangle in red. Show the temperature to the right of the top of the red portion of the thermometer. You may assume the temperature will be in the range 0--100.

     Thermometer Applet

    3. Draw the mouse's maze in a size proportional to the size of the applet's window. You need not change the size of the mouse, but if you are ambitious, you can change its size by calling the Image instance method getScaledInstance:

    Image scaledMouse = mouse.getScaledInstance(width, height, Image.SCALE_DEFAULT);
    where width and height give the new size you would like the mouse to have. Now draw scaledMouse instead of drawing mouse. You can obtain the picture of the mouse  HERE.

    4. Draw the International Olympic Committee logo .. The colors of the circles, left to right, are blue, yellow, black, green, and red.

     Olympic Rings Applet

    5. In Section 2.8, you wrote a program to calculate the price of a coffee order (see page 47 for the complete application). Turn this application into an applet.

     Peets Coffee Applet

    7. You can get a better idea of how colors work in Java by writing an applet to display various red-green-blue (RGB) combinations. Recall that a new color can be created by giving the Color constructor three values, each between 0 and 255, representing the red, green, and blue components. Write an applet with three text fields, labeled Red, Green, and Blue, and a (filled) rectangle. When the user enters a number between 0 and 255 in any of the three fields, a new color is created using the values in those three fields and is displayed as the fill color of the rectangle (rather, a new filled rectangle is drawn over the existing one). In this applet, all three text fields are reactive components, and all should be registered accordingly. However, the actionPerformed method does not need to know which field had a new value entered in it, since it just reads the value in all three fields; thus, the complexities arising from multiple reactive components do not occur.

    RGB Applet

    Chapter 4 -- Decision Making

    Exercises--First Set

    13. The United Parcel Service has the following limitations on the size and weight of packages accepted for shipment: A package cannot exceed 150 pounds or have a combined length plus girth (twice the width plus twice the depth) of over 130 inches. In addition, packages must not exceed 108 inches in length. The minimum charge for an ``oversized'' package (that is, package weighing less than 30 pounds but having a combined length plus girth of over 84 inches) is the same as for a package weighing 30 pounds. Write an applet with text fields for the weight, length, width, and depth of a package to be shipped by UPS, which prints a label indicating whether the package can be shipped under the above restrictions. The label should indicate whether the package can be shipped at all and, if so, whether it is subject to the oversized minimum rate. Note that in an applet containing multiple text fields, all the fields can be filled in by using the tab key to move from one field to the next; actionPerformed is called only when the Enter key is pressed.
     UPS Applet

    14. A (very) simple picture-drawing applet can be written in which the user indicates, with text fields, what type of shape is to be drawn and where it is to appear. Write such an applet. Include a text field for the type of shape---0 for a circle, 1 for a square---and text fields for the center of the shape and its diameter (or the length of a side of the square). (All fields should be filled in by tabbing from one field to another; actionPerformed is called only when the Enter key is pressed.) Don't forget to redefine update, as described in Chapter 3, so that all the shapes show up in the applet's window. If one of the values entered in a text field is invalid, place a label in the applet indicating the error; that label's text should be reset back to the empty string (using errorMessage.setText("")) when actionPerformed is invoked.

     Simple Drawing Applet

    Exercises--Second Set

    9. Many electronic devices use ``seven-segment'' displays to show numbers. ... Write an applet with a text field for input of a number between 0 and 9, which draws the seven-segment version of that number.
      Seven Segment Display Applet

    Exercises--Third Set

    1. In Exercise 8 on page 93 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 an applet, using two TextFields for input.
     Congress Eligibility Applet

    2. In Exercise 3 on page 105 you wrote a switch statement to compute the postage rate for an item, given the weight of the item and the kind of mail class. Write an applet to compute and display the postage rate. Use a TextField to input the weight, and use four grouped radio buttons to select the class of mail.

     Mail Applet

    3. In Exercise 7 on page 77, you wrote an applet in which users entered RGB values (three numbers) and saw the corresponding color. Add to that applet six buttons, labeled Less red, More red, Less green, and so on. When one of these buttons is pushed, the value in the corresponding TextField is incremented or decremented by ten, and the new color displayed.

      Another RGB Applet

    Chapter 5 -- Classes and Methods I: Objects and Instance Methods

    Exercises--First Set

    5. Write a simple number-guessing applet, in which the computer chooses a random number between 1 and 100 and the user tries to guess it. The applet will have a button labeled New game and a text field. When the button is pressed, the computer picks a new random number. Each time the player enters a number in the text field (and presses the Enter key), the applet will display a label indicating whether that number is higher or lower than the secret number. When the user guesses the number, the applet will display a congratulatory message indicating the number of guesses the user needed.
     Number Guessing Applet

    6. Write an applet that shows a clock face, initially set to 8:20, and three buttons, labeled One hour, Ten minutes, and One minute. Each time a button is pressed, the clock advances by that much time.  (Note.   Microsoft Internet Explorer does not work properly with this applet.)

     Clock Applet

    7. Exercise 8 on page 106 described the children's game of Cootie. Turn that game into an applet. You will have one text field to enter the last die throw. You will have instance variables to remember what parts of the Cootie have been drawn, so that you can tell what new part to draw, if any. Since this is a two-player game, you will also need an instance variable to indicate whose turn it is, so that you can announce the correct winner.

      Play Cootie Applet

    Exercises--Second Set

    4. To get some experience with colors, define an applet that shows a single patch of color, with buttons to change the color. Recall from Chapter 3 that colors are objects of class Color, whose constructors include a three-argument constructor in which three integers between 0 and 255 supply the red, green, and blue (RGB) components of the color. A color can be made redder by increasing the red component, and likewise for green and blue. It can be darkened by reducing all three values and lightened by increasing them.
    ...
    Your applet should have buttons for changing the three hues (red, green, and blue) by a fixed percentage, and for changing the brightness. Another button, labeled increase or decrease, indicates in which direction the other buttons operate; clicking on it toggles it. For example, if the direction button says increase, then clicking on the Red button will increase the amount of red shown; clicking on the direction button changes its label to decrease, so that clicking on the Red button decreases the amount of red. The applet should display boxes showing the red, green, and blue components and the combined color, side by side (use setBackground and drawFillRect); each time one of the buttons is pressed, these colors need to be changed.
      RGB Test Applet

    Exercises--Third Set

    4. In computerized drawing programs, one places a shape on the screen and can then perform various operations such as moving, resizing, and rotating. Define the Rectangle class to represent rectangles and perform those operations.
    ...
    Write an applet to test this class. It should start with a square drawn in the middle of the applet'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.
     Rectangle Manipulation Applet

    5. Write a tic-tac-toe-playing applet. ... You should start with the tic-tac-toe board drawn in the applet's window with an X in the upper-left corner. There should be three buttons: ``down'' should move the X down (or back up to the top row if it is on the bottom row); ``right'' should move the X to the right (or back to the left column if it it is in the right column); and ``okay'' should leave the X where it is and go on to the next move. The next move should begin by placing O in a free space and letting the ``down'' and ``right'' keys move it to the next free space in the indicated direction. Again, pressing the ``okay'' button ends O's move. The game should continue like this until X or O wins, or all spaces are filled, at which time an appropriate label should be displayed.

      Tic Tac Toe Applet

    Exercises--Fourth Set

    1. The beauty of having Eyes as a separate class is that it is easy to create new eyes, and to create different kinds of eyes.
    1. Add eyes in the other two corners of the applet window.
    2. Modify the applet so that the eyes change only when the mouse is clicked. You will need to use the MouseListener interface described in Table 5.3.
    3. Define a class ShyEyes that is like Eyes except that its pupils always turn away from the cursor. Define your applet to contain both Eyes and ShyEyes.
    4. Modify the Eyes applet so that the eyes ``sleep'' when the mouse is outside the applet, and ``awaken'' when it moves inside the applet. You can draw a sleeping eye by drawing a horizontal diameter instead of the pupil.
    5. Modify the Eyes applet further so that when the cursor is inside the applet area, the eyes sleep when you press on the mouse button, and awaken when you release.
     Shy and Sleepy Eyes Applet

    2. Write a tic-tac-toe-playing applet similar to the one in Exercise 5 on page 160, but with this difference: the user indicates the next move by clicking the mouse in the desired empty square instead of pushing buttons.

     Tic Tac Toe (with mouse) Applet

    3. Write an applet similar to the one in Exercise 4 on page 159, but using the mouse to indicate how to move or reshape the rectangle. This applet 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, but 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.

     Rectangle Manipulation Applet (clicking with mouse)

    4. A somewhat more difficult version of Exercise 3 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.

      Rectangle Manipulation Applet (dragging with mouse)

    Chapter 6 -- Iteration

    Exercises--First Set

    10. Write an applet 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, say (r1, g1, b1) and (r2, g2, b2), show a bar of colors consisting of ten 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.
     Color Bar Applet

    11. Write an applet to draw regular polygons. The applet should have a single text field. When the user enters a positive integer n in the text field, the applet draws an n-gon in its window.

     Polygon Drawing Applet

    12. Write a method

    void drawDottedLine(Graphics g, int x0, int y0, int x1, int y1)
    that draws a dotted line from point (x0, y0) to point (x1, y1). Using this method, modify the code from Section 3.12 (page 70) to draw the mouse's maze with dotted lines spanning the openings between cells (as shown in the pictures in Chapter 1).
      Draw a Mouse with a Dotted Maze Applet

    Exercises--Second Set

    7. Write an applet to draw sine curves. Two text fields are used to enter the lower and upper x values, x0 and x1, and a curve sin x is drawn between those two values.
     Draw Sine Curve Applet

    8. Write an applet in which a ball bounces around within the applet's window. When the circle hits a side of the applet's window, change the direction.

      Bouncing Ball Applet

    Exercises--Third Set

    1. Change the animations in both Surprise and Surprise2 so that the circle grows larger and then grows smaller and disappears.
     Modified Surprise2 Applet

    2. Animate the clock applet you wrote for Exercise 6 on page 132, as follows: When the time is incremented, instead of just showing the new position of the minute and hour hands, show the hand moving to that new position.   (Note.  Microsoft Internet Explorer does not work properly with this applet.)

     Animated Clock Applet

    Chapter 7 -- One Dimensional Arrays

    Exercises--First Set

    9. The function int findMax (double[] A) finds the index in A at which it has its maximum value: ...Write an applet that animates the findMax function. 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 (Color.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.
     Find Max Animation Applet

    10. Create a freehand-drawing applet. Start with an applet window that is empty except for three buttons, Clear, Undo, and Undo last line. When the user clicks-and-drags the mouse, the line it traces out should be drawn (and stored in an arrray), ending when the mouse button is released. The user should be able to draw a many lines as he or she wishes, subject to a limit on the number of points the applet can store (say, 10,000). The Clear button should clear the screen and empty the array; the Undo button should erase the last point that was added; the Undo last line should erase the entire last line drawn. The Undo buttons can be pressed multiple times, erasing more and more each time. Of course, at any time the user can begin drawing a new line by clicking and dragging.

     Freehand Drawing Applet

    11. Modify the RandomCircles applet from Section 3.7 (page 73) to draw circles filled with a specified color. Use the idea of the ColorTest applet (Exercise 4 on page 138) to let the user specify a color. Specifically, the applet should have six buttons: Circle, More (which toggles to Less and back), Red, Green, Blue, and Bright. The Circle button places a random circle in the applet, filled with the current color. Whenever any of the other buttons is pressed, this indicates a change in the color, and all the circles should be redrawn in the new color.

      RGB Random Circles Applet

    Exercises--Second Set

    Exercises--Third Set

    2. You can create a simple drawing program in an applet quite easily. In these programs, the user pushes a button to select a type of graphical object, such as a rectangle or circle, and then uses the mouse to create that object at the desired location and size. We'll start with one type of graphical object, polygons, and then add circles, but you can continue as far as you like.
    1. Create an applet in which the user can construct a polygon by clicking on its vertices with the mouse. ...
    2. ... allow for more than one polygon... you'll need to have two buttons in the applet, one to start a new polygon and one to end the polygon.
    3. ... Add a button for drawing a circle. After pushing this button, the next mouse press (pushing the mouse button but not releasing it) defines the center of the circle; releasing it defines the radius.
     Draw Polygons and Circles Applet

    Chapter 8 -- Classes and Methods II: Static Methods and Variables

    Exercises--First Set

    6. Create an applet that displays the time in various cities, including your city, New York, Paris, and Moscow. It can display it either in standard format or in military format. You should have text fields to input hour and minutes, and checkboxes for AM/PM (for input) and for standard/military format.
      Time in Various Cities Applet

    Exercises--Second Set

    Exercises--Third Set

     
    7.  Write an applet to determine a zodiac sign, given the month and the day. There should be a checkbox group for the month and a text field for the day. Try to find GIF or JPEG images representing the signs of the zodiac, and display the correct one along side the name of the sign.
     Zodiac Signs Applet

    Exercises--Fourth Set

    1. Reprogram the Temperature Conversion applet from Chapter 3 so that resizing preserves a pleasing appearance.  (Note.  You cannot resize applets from within browsers.  You must run this using appletviewer to see its effects.)
     Temperature Conversion Applet (resizable)

    2. Reprogram the Body Mass applet above 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 applet when increasing this message size.   (Note.  You can see some of the effects using a browser, but you can resize and see other effects if you run this using appletviewer.)

     Body Mass Applet (resizable)

    3. Modify our CalendarApplet so that today's date is enclosed in a rectangle.  (See Exercise 4 below.)

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

      Embellished Calendar Applet
     

    Chapter 9 -- Nested Loops and Two-Dimensional Arrays

    Exercises--First Set

    9. In Exercise 12 on page 185, you wrote a method to draw dotted lines in an applet: ... Write a method
    void drawDottedPolygon(Graphics g, Point[] points)
    that connects all the points in an array of points by dotted lines (including connecting the last point to the first). To test it, write an applet 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.
     Draw Dotted Polygon Applet

    10. Write applets to draw ``bar charts.'' Given an array of integers (entered by using a TextField, after which the Draw Bar Chart button must be pressed to create the bar chart), the values should be shown by vertical bars placed side-by-side. The height of the bars should be scaled so that the tallest one fits just inside the applet's window without hitting the buttons; their width should be calculated so that all the bars fill the window with a small gap on each side. Write three variants.

    1. Each bar is filled with evenly-spaced vertical lines.
    2. Each bar is filled by five horizontal lines.
    3. Bars alternate between vertical and horizontal fill.
     Draw Bar Charts Applet

    Exercises--Second Set

    7.
    1. Program Conway's Game of Life as an applet. 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 (see Section 5.3 on page 173), and provide a button to start the simulation.
    2. Keep track of the age of each cell, and display different aged cells in different colors.
    3. Life Applet

    Exercises--Third Set

    Chapter 10 -- Strings, Characters, and File I/O

    Exercises--First Set

    Exercises--Second Set

    Chapter 11 -- Recursion

    Exercises--First Set

    Exercises--Second Set

    Exercises--Third Set

    Exercises--Fourth Set

    Exercises--Fifth Set

    2. The ... Sierpinski gasket is closely connected to the Towers of Hanoi problem... Write an applet to draw members of this sequence of curves.
      Sierpinski Gasket Applet

    Chapter 12 -- The Java API: Packages, Inheritance, Interfaces and Exceptions

    Exercises--First Set

    (Note.  Although these exercises are not presented as applet exercises, it is instructive to see them applied to the applet version of MouseMazeApplet.)

    1. Sometimes a superclass acts as a ``conduit,'' in which a client invokes a method in the superclass; that method not only invokes a method that is defined in a subclass, but it also takes some additional action or records some information.
    Add such 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. You'll want to define a list class to record the configurations for the mouse. The client of Mouse (namely MouseMaze) 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.  (See Exercise 2 below.)

    2. 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. Namely, 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 (location and direction) that the mouse has already experienced, makeRecordMove() should refuse that suggestion, and should invoke another method---makeAlternativeMove(int attempt)---which will choose a different move. The makeRecordMove() method may similarly 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.

      Mouse in a Maze with Backup Applet
     

    Chapter 13 -- Case Study: The Game of Reversi

    Exercises--First Set

    4. The Smart Player isn't really so smart! Simply counting the number of stones flipped is rather short-sighted. 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. (It is possible to devise even more complex weighting strategies, depending on whether a particular square is weak or strong in the present configuration. For example, an edge square is useless if one of the adjacent edge squares is occupied by the opponent and the other is vacant---for then the opponent can immediately recapture your edge square.) Program such a SmarterPlayer.   (See Exercise 5 below.)

    5. Again, the Smarter Player 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 Expert Player might utilize 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-ahead carry this idea even further!

    In general, n-ply look-ahead involves building a game tree, with the present Board leading to several successor Boards (one for each of the possible moves), 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 Smart Player in Exercise 4. At the level above those terminal Boards, the opponent will presumably select his best move by choosing the minimum value of the Boards below. At the level above that, the Expert Player selects the maximum, etc. This is the strategy if the look-ahead is an even number. If it is an odd number, then the Expert selects from bottom most Boards, and the role of minimizing and maximizing is reversed.

    Thus, the Expert Player implements a pair of mutually recursive evaluation methods, one to maximize results, and one to minimize results: ... For obvious reasons, this technique is called a min-max game-playing strategy.  Program such an Expert Player.

    Reversi Game Applet with Choice of Player Type