created 08/13/99


Chapter 22 Programming Exercises

Many of your programs from previous chapters can be used with file input and output without modification. Pick a few of them and play. Perhaps make a few modifications, such as removing prompts.

Exercise 1 --- Maximum

Write a program that reads 5 integers from a file, computes their and their maximum and prints these values to the screen. Do this by modifying the summing program from the chapter. Insert a new int variable called max which you should initialize to the first value in the file. This will call for an extra set of input statements before the loop starts. To compute the maximum you will need an if statement nested inside the loop.

Click here to go back to the main menu.


Exercise 2 --- Floating Point Input

Write a program that adds up five floating point numbers input from a file (or from the keyboard.) As always with input from text files, use readLine() to get a string of characters. This string must contain only characters that designate a floating point number, like -0.184 or 1.23E+12. Characters that designate an integer, like 412 will also work for floating point input. Recall how to convert a string into a floating point number:

String lineIn;
double val;
. . . 
val  = ( Double.valueOf( lineIn  ) ).doubleValue();

Click here to go back to the main menu.


Exercise 3 --- Optional Prompts

Modify the program that adds five integers so that it first asks if further prompts are desired. The user enters "yes" or "no" (just once, at the beginning). Now the loop either prompts or does not prompt for each of the integers to be input.

You will need to use the equals() method of String. Set a boolean variable to true or false depending on the user's first input string. There will be an if statement inside the loop that determines if a prompt is written.

Click here to go back to the main menu.