Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^242) | File Objects and Looping Statements
Of course, nested loops themselves can contain nested loops (called doubly nested loops),
which can contain nested loops (triply nested loops), and so on. You can use this design process
for any number of levels of nesting. The trick is to defer details—that is, focus on the outer-
most loop first, and treat each new level of nested loop as a single step within the loop that
contains it.
It’s also possible for the process within a loop to include more than one loop. For exam-
ple, here’s an algorithm that reads students’ test and homework scores from a file and prints
their average on another file:
The steps for reading and averaging the scores require us to design two separate loops. All
of these loops are sentinel-controlled.
This kind of complex control structure would be difficult to read if written out in full. It
contains too many variables, conditions, and steps to remember at one time. When an al-
gorithm becomes so complex, it is an indication that we failed to identify objects that would
naturally hide some of this complexity via abstraction. In this case, we could create a new
class with methods that get the scores of one type for a student and return their average. We
could call the new class ScoreFileReader. The individual loops would then be hidden in the
class, and the application would look essentially like the algorithm above.


5.3 Mutable and Immutable Objects


In this section, we see how objects are divided into two distinct categories,mutableandim-
mutable.The distinction determines their behavior when they are passed as arguments to meth-
ods. When a method is executed, it uses copies of the values of the arguments. Because of how
reference types are stored, however, the effect of passing mutable or immutable arguments
varies. Thus far, most of our objects have been immutable, but in the Case Study we will create
a class with mutable objects. First we review how arguments and parameters work in general.
With primitive types, such as int,double, and boolean, the parameter receives a copy of
the value of the argument. The method can freely use and change the copy in the parame-
ter. When we pass a variable as an argument to a parameter, it is easy to think that the two
identifiers are connected in some way, as if the parameter becomes a synonym for the ar-
gument. In reality, their only connection occurs at the moment when the value of the argu-
ment is copied to the parameter. Otherwise, they remain independent of each other. That is,
operations on the parameter do not affect the argument.

whileNOT EOF
Input line with name
Print name
Read and average test scores until a negative score is input
Print average test score
Read and average homework scores until a negative score is input
Print average homework score
Output newline
Free download pdf