Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^240) | File Objects and Looping Statements
Here’s the output on outFilefrom the code given the input used for our trace:





  • End
    Because starCountand loopCountare variables, their values remain the same until they
    are explicitly changed, as indicated by the repeating values in Table 5.1. The values of the log-
    ical expressions line != nulland loopCount <= starCountexist only when the test is made.
    We indicate this fact with dashes in those columns at all other times.


Designing Nested Loops


To design a nested loop, we begin with the outer loop. The process being repeated includes
the nested loop as one of its steps. Because that step is complex, we defer designing it; we
will come back to it later. Then we can design the nested loop just as we would any other loop.
As an example, here’s the design process for the outer loop in the preceding code
segment:
1.What condition ends the loop?EOF is reached in the input.
2.How should the condition be initialized?A priming read should be performed before
the loop starts.
3.How should the condition be updated?An input statement should occur at the end
of each iteration.
4.What is the process being repeated?Using the value of the current input integer, the
code should print that many asterisks across one output line.
5.How should the process be initialized?No initialization is necessary.
6.How should the process be updated?A sequence of asterisks is output and then a
newline character is output. There are no counter variables or sums to update.
7.What is the state of the code on exiting the loop?The file dataFileis at EOF,starCount
contains the last integer read from the input stream, and the rows of asterisks
have been printed along with a concluding message.
From the answers to these questions, we can write this much of the algorithm:

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf