[ Chapter Index | Main Index ]

Programming Exercises for Chapter 4


This page contains several exercises for Chapter 4 in Introduction to Programming Using Java. For each exercise, a link to a possible solution is provided. Each solution includes a discussion of how a programmer might approach the problem and interesting points raised by the problem or its solution, as well as complete source code of the solution.


Exercise 4.1:

To "capitalize" a string means to change the first letter of each word in the string to upper case (if it is not already upper case). For example, a capitalized version of "Now is the time to act!" is "Now Is The Time To Act!". Write a subroutine named printCapitalized that will print a capitalized version of a string to standard output. The string to be printed should be a parameter to the subroutine. Test your subroutine with a main() routine that gets a line of input from the user and applies the subroutine to it.

Note that a letter is the first letter of a word if it is not immediately preceded in the string by another letter. Recall from Exercise 3.4 that there is a standard boolean-valued function Character.isLetter(char) that can be used to test whether its parameter is a letter. There is another standard char-valued function, Character.toUpperCase(char), that returns a capitalized version of the single character passed to it as a parameter. That is, if the parameter is a letter, it returns the upper-case version. If the parameter is not a letter, it just returns a copy of the parameter.

See the Solution


Exercise 4.2:

The hexadecimal digits are the ordinary, base-10 digits '0' through '9' plus the letters 'A' through 'F'. In the hexadecimal system, these digits represent the values 0 through 15, respectively. Write a function named hexValue that uses a switch statement to find the hexadecimal value of a given character. The character is a parameter to the function, and its hexadecimal value is the return value of the function. You should count lower case letters 'a' through 'f' as having the same value as the corresponding upper case letters. If the parameter is not one of the legal hexadecimal digits, return -1 as the value of the function.

A hexadecimal integer is a sequence of hexadecimal digits, such as 34A7, ff8, 174204, or FADE. If str is a string containing a hexadecimal integer, then the corresponding base-10 integer can be computed as follows:

value = 0;
for ( i = 0; i < str.length();  i++ )
   value = value*16 + hexValue( str.charAt(i) );

Of course, this is not valid if str contains any characters that are not hexadecimal digits. Write a program that reads a string from the user. If all the characters in the string are hexadecimal digits, print out the corresponding base-10 value. If not, print out an error message.

See the Solution


Exercise 4.3:

Write a function that simulates rolling a pair of dice until the total on the dice comes up to be a given number. The number that you are rolling for is a parameter to the function. The number of times you have to roll the dice is the return value of the function. The parameter should be one of the possible totals: 2, 3, ..., 12. The function should throw an IllegalArgumentException if this is not the case. Use your function in a program that computes and prints the number of rolls it takes to get snake eyes. (Snake eyes means that the total showing on the dice is 2.)

See the Solution


Exercise 4.4:

This exercise builds on Exercise 4.3. Every time you roll the dice repeatedly, trying to get a given total, the number of rolls it takes can be different. The question naturally arises, what's the average number of rolls to get a given total? Write a function that performs the experiment of rolling to get a given total 10000 times. The desired total is a parameter to the subroutine. The average number of rolls is the return value. Each individual experiment should be done by calling the function you wrote for Exercise 4.3. Now, write a main program that will call your function once for each of the possible totals (2, 3, ..., 12). It should make a table of the results, something like:

Total On Dice     Average Number of Rolls
-------------     -----------------------
       2               35.8382
       3               18.0607
       .                .
       .                .

See the Solution


Exercise 4.5:

This exercise asks you to write a few lambda expressions and a function that returns a lambda expression as its value. Suppose that a function interface ArrayProcessor is defined as

public interface ArrayProcessor {
    double apply( double[] array );
}

Write a class that defines four public static final variables of type ArrayProcessor that process an array in the following ways: find the maximum value in the array, find the minimum value in an array, find the sum of the values in the array, and find the average of the values in the array. In each case, the value of the variable should be given by a lambda expression. The class should also define a function

public static ArrayProcessor counter( double value ) { ...

This function should return an ArrayProcessor that counts the number of times that value occurs in an array. The return value should be given as a lambda expression.

The class should have a main() routine that tests your work. The program that you write for this exercise will need access to the file ArrayProcessor.java, which defines the functional interface.

See the Solution


Exercise 4.6:

The sample program RandomMosaicWalk.java from Section 4.7 shows a "disturbance" that wanders around a grid of colored squares. When the disturbance visits a square, the color of that square is changed. Here's an idea for a variation on that program. In the new version, all the squares start out with the default color, black. Every time the disturbance visits a square, a small amount is added to the green component of the color of that square. The result will be a visually interesting effect, as the path followed by the disturbance gradually turns a brighter and brighter green.

Write a subroutine that will add 25 to the green component of one of the squares in the mosaic. (But don't let the green component go over 255, since that's the largest legal value for a color component.) The row and column numbers of the square should be given as parameters to the subroutine. Recall that you can discover the current green component of the square in row r and column c with the function call Mosaic.getGreen(r,c). Use your subroutine as a substitute for the changeToRandomColor() subroutine in the program RandomMosaicWalk2.java. (This is the improved version of the program from Section 4.8 that uses named constants for the number of rows, number of columns, and square size.) Set the number of rows and the number of columns to 80. Set the square size to 5.

By default, the rectangles in the mosaic have a "3D" appearance and a gray border that makes them look nicer in the random walk program. But for this program, you want to turn off that effect. To do so, call Mosaic.setUse3DEffect(false) in the main program.

Don't forget that you will need Mosaic.java and MosaicCanvas.java to compile and run your program, since they define non-standard classes that are required by the program.

See the Solution


Exercise 4.7:

For this exercise, you will do something even more interesting with the Mosaic class that was discussed in Section 4.7. (Again, don't forget that you will need Mosaic.java and MosaicCanvas.java to compile and run your program.)

The program that you write for this exercise should start by filling a mosaic with random colors. Then repeat the following until the user closes the mosaic window: Select one of the rectangles in the mosaic at random. Then select one of the neighboring rectangles—above it, below it, to the left of it, or to the right of it. Copy the color of the originally selected rectangle to the selected neighbor, so that the two rectangles now have the same color.

As this process is repeated over and over, it becomes more and more likely that neighboring squares will have the same color. The result is to build up larger color patches. On the other hand, once the last square of a given color disappears, there is no way for that color to ever reappear. (Extinction is forever!) If you let the program run long enough, eventually the entire mosaic will be one uniform color.

See the Solution


Exercise 4.8:

Write a program that administers a basic addition quiz to the user. There should be ten questions. Each question is a simple addition problem such as 17 + 42, where the numbers in the problem are chosen at random (and are not too big). The program should ask the user all ten questions and get the user's answers. After asking all the questions, the user should print each question again, with the user's answer. If the user got the answer right, the program should say so; if not, the program should give the correct answer. At the end, tell the user their score on the quiz, where each correct answer counts for ten points.

The program should use three subroutines, one to create the quiz, one to administer the quiz, and one to grade the quiz. It can use three arrays, with three global variables of type int[], to refer to the arrays. The first array holds the first number from every question, the second holds the second number from every questions, and the third holds the user's answers.

See the Solution


[ Chapter Index | Main Index ]