New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.

Get the latest Java books 

h t t p : / /w w w . j a v a c o f f e e b r e a k . c
o m /

Programming Exercises
For Chapter 8
THIS PAGE CONTAINS programming exercises based on material from Chapter 8 of this online Java textbook. Each exercise has a link to a discussion of one possible solution of that exercise.
Exercise 8.1: An example in Section 8.2 tried to answer the question, How many random people do you have to select before you find a duplicate birthday? The source code for that program can be found in the file BirthdayProblemDemo.java. Here are some related questions:
 How many random people do you have to select before you find three people who share the same birthday? (That is, all three people were born on the same day in the same month, but not necessarily in the same year.)
 Suppose you choose 365 people at random. How many different birthdays will they have? (The number could theoretically be anywhere from 1 to 365).
 How many different people do you have to check before you've found at least one person with a birthday on each of the 365 days of the year?
Write three programs to answer these questions. Like the example program, BirthdayProblemDemo, each of your programs should simulate choosing people at random and checking their birthdays. (In each case, ignore the possibility of leap years.)
Exercise 8.2: Write a program that will read a sequence of positive real numbers entered by the user and will print the same numbers in sorted order from smallest to largest. The user will input a zero to mark the end of the input. Assume that at most 100 positive numbers will be entered.
Exercise 8.3: A polygon is a geometric figure made up of a sequence of connected line segments. The points where the line segments meet are called the vertices of the polygon. The Graphics class includes commands for drawing and filling polygons. For these commands, the coordinates of the vertices of the polygon are be stored in arrays. If g is a variable of type Graphics then
 g.drawPolygon(xCoords, yCoords, pointCt) will draw the outline of the polygon with vertices at (xCoords[0],yCoords[0]), (xCoords[1],yCoords[1]), ..., (xCoords[pointCt1],yCoords[pointCt1]). The third parameter, pointCt, is an int that specifies the number of vertices of the polygon. Its value should be 3 or greater. The first two parameters are arrays of type int[]. Note that the polygon automatically includes a line from the last point, (xCoords[pointCt1],yCoords[pointCt1]), back to the starting point (xCoords[0],yCoords[0]).
 g.fillPolygon(xCoords, yCoords, pointCt) fills the interior of the polygon with the current drawing color. The parameters have the same meaning as in the drawPolygon() method. Note that it is OK for the sides of the polygon to cross each other, but the interior of a polygon with selfintersections might not be exactly what you expect.
Write a little applet that lets the user draw polygons. As the user clicks a sequence of points, count them and store their x and ycoordinates in two arrays. These points will be the vertices of the polygon. Also, draw a line between each consecutive pair of points to give the user some visual feedback. When the user clicks near the starting point, draw the complete polygon. Draw it with a red interior and a black border. The user should then be able to start drawing a new polygon. When the user shiftclicks on the applet, clear it.
There is no need to store information about the contents of the applet. The paint() method can just draw a border around the applet. The lines and polygons can be drawn using a graphics context, g, obtained with the command "g = getGraphics();".
You can try my solution. Note that nothing is drawn on the applet until you click the second vertex of the polygon. You have to click within two pixels of the starting point to see a filled polygon.
Exercise 8.4: For this problem, you will need to use an array of objects. The objects belong to the class MovingBall, which I have already written. You can find the source code for this class in the file MovingBall.java. A MovingBall represents a circle that has an associated color, radius, direction, and speed. It is restricted to moving in a rectangle in the (x,y) plane. It will "bounce back" when it hits one of the sides of this rectangle. A MovingBall does not actually move by itself. It's just a collection of data. You have to call instance methods to tell it to update its position and to draw itself. The constructor for the MovingBall class takes the form
new MovingBall(xmin, xmax, ymin, ymax)where the parameters are integers that specify the limits on the x and y coordinates of the ball. In this exercise, you will want balls to bounce off the sides of the applet, so you will create them with the constructor call "new MovingBall(0, getSize().width, 0, getSize().height)". The constructor creates a ball that initially is colored red, has a radius of 5 pixels, is located at the center of its range, has a random speed between 4 and 12, and is headed in a random direction. If ball is a variable of type MovingBall, then the following methods are available:
 ball.draw(g)  draw the ball in a graphics context. The parameter, g, must be of type Graphics. (The drawing color in g will be changed to the color of the ball.)
 ball.travel()  change the (x,y)coordinates of the ball by an amount equal to its speed. The ball has a certain direction of motion, and the ball is moved in that direction. Ordinarily, you will call this once for each frame of an animation, so the speed is given in terms of "pixels per frame". Calling this routine does not move the ball on the screen. It just changes the values of some instance variables in the object. The next time the object's draw() method is called, the ball will be drawn in the new position.
 ball.headTowards(x,y)  change the direction of motion of the ball so that it is headed towards the point (x,y). This does not affect the speed.
These are the methods that you will need for this exercise. There are also methods for setting various properties of the ball, such as ball.setColor(color) for changing the color and ball.setRadius(radius) for changing its size. See the source code for more information.
For this exercise, you should create an applet that shows an animation of 25 balls bouncing around on a black background. Your applet can be defined as a subclass of SimpleAnimationApplet, which was first introduced in Section 3.7. Use an array of type MovingBall[] to hold the 25 balls. The drawFrame() method in your applet should move all the balls and draw them.
In addition, your applet should implement the MouseListener and MouseMotionListener interfaces. When the user presses the mouse or drags the mouse, call each of the ball's headTowards() methods to make the balls head towards the mouse's location.
Here is my solution. Try clicking and dragging on the applet:
Exercise 8.5: To do this exercise, you need to know the material on components and layouts from Chapter 7. Write an applet that draws pie charts based on data entered by the user. A pie chart is a circle divided into colored wedges. Each wedge of the pie corresponds to one number in an array of positive numbers. The number of degrees in the wedge is proportional to the corresponding number. If g is a variable of type Graphics, then a wedge can be drawn with the command
g.fillArc(left, top, width, height, startAngle, degrees);All the parameters in this command are integers. The first four parameters give the left edge, top edge, width, and height of a rectangle containing the "pie". For a circle, the width and height must be the same. The fifth parameter tells the starting angle of the wedge, and the sixth tells the number of degrees in the wedge.
Your applet should include 12 TextFields where the user can enter the data for the pie chart. You will need an array of type TextField[] to keep track of these input boxes. Section 7.4 has an example that shows how to get a number of type double from an input box. You should ignore any input boxes that are empty. Use the data from the nonempty input boxes for the pie chart.
The applet should have a button that the user clicks to draw the pie chart. And it should have a subclass of the Canvas class that will display the pie chart. I suggest that this class include an instance variable of type int[] to store the data needed for the pie chart. The data that you need is the angles of the dividing lines between the wedges. This is not the same as the data from the input boxes, but it can be computed from that data. Suppose the user's data is data[0], data[1], ..., data[dataCt1]. Let dataSum be the sum of all the user's data, data[0] + data[1] + ... + data[dataCt1]. Let sum be the sum of the first i data values, data[0] + data[1] + ... + data[i1]. Then the angle for the ith dividing line in the pie chart is given by "(int)(360*sum/dataSum + 0.5)". (The "360" is there because it represents the number of degrees in a full circle. The "+0.5" is there so the answer will be rounded to the nearest integer rather than truncated downwards.)
Here is my solution:
Exercise 8.6: The game of Go Moku (also known as Pente or Five Stones) is similar to TicTacToe, except that it played on a much larger board and the object is to get five squares in a row rather than three. Players take turns placing pieces on a board. A piece can be placed in any empty square. The first player to get five pieces in a row  horizontally, vertically, or diagonally  wins. If all squares are filled before either player wins, then the game is a draw. Write an applet that lets two players play Go Moku against each other.
Your applet will be simpler than the Checkers applet from Section 8.5. Play alternates strictly between the two players, and there is no need to hilite the legal moves. You will only need two classes, a short applet class to set up the applet and a GoMokuCanvas class to draw the board and do all the work of the game. Nevertheless, you will probably want to look at the source code for the checkers applet, Checkers.java, for ideas about the general outline of the program.
The hardest part of the program is checking whether the move that a player makes is a winning move. To do this, you have to look in each of the four possible directions from the square where the user has placed a piece. You have to count how many pieces that player has in a row in that direction. If the number is five or more in any direction, then that player wins. As a hint, here is part of the code from my applet. This code counts the number of pieces that the user has in a row in a specified direction. The direction is specified by two integers, dirX and dirY. The values of these variables are 0, 1, or 1, and at least one of them is nonzero. For example, to look in the horizontal direction, dirX is 1 and dirY is 0.
int ct = 1; // Number of pieces in a row belonging to the player. int r, c; // A row and column to be examined r = row + dirX; // Look at square in specified direction. c = col + dirY; while ( r >= 0 && r < 13 && c >= 0 && c < 13 && board[r][c] == player ) { // Square is on the board, and it // contains one of the players's pieces. ct++; r += dirX; // Go on to next square in this direction. c += dirY; } r = row  dirX; // Now, look in the opposite direction. c = col  dirY; while ( r >= 0 && r < 13 && c >= 0 && c < 13 && board[r][c] == player ) { ct++; r = dirX; // Go on to next square in this direction. c = dirY; }Here is my applet. It uses a 13by13 board. You can do the same or use a normal 8by8 checkerboard.
[ Chapter Index  Main Index ]