Java Reference
In-Depth Information
30
System.out.printf(
"Class average is %d%n"
, average);
31
}
32
}
// end class ClassAverage
Enter grade:
67
Enter grade:
78
Enter grade:
89
Enter grade:
67
Enter grade:
87
Enter grade:
98
Enter grade:
93
Enter grade:
85
Enter grade:
82
Enter grade:
100
Total of all 10 grades is 846
Class average is 84
Fig. 4.8
|
S
olving the class-average problem using counter-controlled repetition. (Part 2 of 2.)
Local Variables in Method
main
Line 10 declares and initializes
Scanner
variable
input
, which is used to read values
entered by the user. Lines 13, 14, 20 and 26 declare local variables
total
,
gradeCounter
,
grade
and
average
, respectively, to be of type
int
. Variable
grade
stores the user input.
These declarations appear in the body of method
main
. Recall that variables declared
in a method body are local variables and can be used only from the line of their declaration
to the closing right brace of the method declaration. A local variable's declaration must
appear
before
the variable is used in that method. A local variable cannot be accessed out-
side the method in which it's declared. Variable
grade
, declared in the body of the
while
loop, can be used only in that block.
Initialization Phase: Initializing Variables
total
and
gradeCounter
The assignments (in lines 13-14) initialize
total
to
0
and
gradeCounter
to
1
. These ini-
tializations occur
before
the variables are used in calculations.
Common Programming Error 4.3
Using the value of a local variable before it's initialized results in a compilation error. All
local variables must be initialized before their values are used in expressions.
Error-Prevention Tip 4.3
Initialize each total and counter, either in its declaration or in an assignment statement.
Totals are normally initialized to 0. Counters are normally initialized to 0 or 1, depend-
ing on how they're used (we'll show examples of when to use 0 and when to use 1).
Processing Phase: Reading 10 Grades from the User
Line 17 indicates that the
while
statement should continue looping (also called
iterating
)
as long as
gradeCounter
's value is less than or equal to 10. While this condition remains
true
, the
while
statement repeatedly executes the statements between the braces that de-
limit its body (lines 18-23).