Java Reference
In-Depth Information
1
Set total to zero
2
Set grade counter to one
3
4
While grade counter is less than or equal to ten
5
Prompt the user to enter the next grade
6
Input the next grade
7
Add the grade into the total
8
Add one to the grade counter
9
10
Set the class average to the total divided by ten
11
Print the class average
Fig. 4.7 | Pseudocode algorithm that uses counter-controlled repetition to solve the class-
average problem.
Implementing Counter-Controlled Repetition
In Fig. 4.8, class ClassAverage 's main method (lines 7-31) implements the class-averaging
algorithm described by the pseudocode in Fig. 4.7—it allows the user to enter 10 grades,
then calculates and displays the average.
1
// Fig. 4.8: ClassAverage.java
2
// Solving the class-average problem using counter-controlled repetition.
3
import java.util.Scanner; // program uses class Scanner
4
5
public class ClassAverage
6
{
7
public static void main(String[] args)
8
{
9
// create Scanner to obtain input from command window
10
Scanner input = new Scanner(System.in);
11
12
// initialization phase
13
int total = 0 ; // initialize sum of grades entered by the user
14
int gradeCounter = 1 ; // initialize # of grade to be entered next
15
16
// processing phase uses counter-controlled repetition
17
while (
gradeCounter <= 10
) // loop 10 times
18
{
19
System.out.print( "Enter grade: " ); // prompt
20
int grade = input.nextInt(); // input next grade
21
total = total + grade; // add grade to total
22
gradeCounter = gradeCounter + 1 ; // increment counter by 1
23
}
24
25
// termination phase
26
int average = total / 10 ; // integer division yields integer result
27
28
// display total and average of grades
29
System.out.printf( "%nTotal of all 10 grades is %d%n" , total);
Fig. 4.8 | S olving the class-average problem using counter-controlled repetition. (Part 1 of 2.)
 
Search WWH ::




Custom Search