Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^254) | File Objects and Looping Statements
Given that sentinel-controlled loops involve a priming read, it is especially important to
verify that the first and last data sets are processed properly.
Testing and Debugging Hints
1.For each file that an application uses, check that all five of the required steps
are performed: import the packagejava.io.*, declare a variable of the given
file class, instantiate the file object, use the methods associated with the file
object to perform input or output operations, and close the file when you are
done using it.
2.Remember that the constructor for a FileReaderor a FileWritercan be passed
the name of the disk file, but the constructor for a BufferedReadermust be
passed an object of type FileReaderand the constructor for a PrintWritermust
be passed a FileWriterobject.
3.If you use file I/O, remember that mainmust have the throwsIOException
clause appended to its heading.
4.Plan your test data carefully to test all sections of an application.
5.Beware of infinite loops, where the expression in the whilestatement never
becomes false. The symptom: the application doesn’t stop.
6.If you have created an infinite loop, check your logic and the syntax of your
loops. Be sure no semicolon follows immediately after the right parenthesis of
the whilecondition:
while(Expression); // Wrong
Statement
This semicolon causes an infinite loop in most cases; the compiler thinks the
loop body is the null statement (the do-nothing statement composed only of
a semicolon). In a count-controlled loop, make sure the loop control variable
is incremented within the loop. In a flag-controlled loop, make sure the flag
eventually changes.
7.Check the loop termination condition carefully, and verify that something in
the loop causes it to be met. Watch closely for values that cause one iteration
too many or too few (the “off-by-one” syndrome).
8.Write out the consistent, predictable part of a loop’s behavior in each
iteration. Look for patterns that it establishes. Are they just what you want?
Perform an algorithm walk-through to verify that all of the appropriate condi-
tions occur in the right places.
9.Trace the execution of the loop by hand with a code walk-through. Simulate the
first few passes and the last few passes very carefully to see how the loop really
behaves.

Free download pdf