Java Reference
In-Depth Information
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
14
int gradeCounter = 0 ; // initialize # of grades entered so far
15
16
// processing phase
17
// prompt for input and read grade from user
System.out.print( "Enter grade or -1 to quit: " );
int grade = input.nextInt();
18
19
20
21
// loop until sentinel value read from user
22
while (grade != -1 )
23
{
24
total = total + grade; // add grade to total
25
gradeCounter = gradeCounter + 1 ; // increment counter
26
27
// prompt for input and read next grade from user
System.out.print( "Enter grade or -1 to quit: " );
grade = input.nextInt();
28
29
30
}
31
32
// termination phase
33
// if user entered at least one grade...
34
if (
gradeCounter != 0
)
35
{
36
// use number with decimal point to calculate average of grades
double average = ( double ) total / gradeCounter;
37
38
39
// display total and average (with two digits of precision)
40
System.out.printf( "%nTotal of the %d grades entered is %d%n" ,
41
gradeCounter, total);
42
System.out.printf( "Class average is %.2f%n" , average);
43
}
44
else // no grades were entered, so output appropriate message
45
System.out.println( "No grades were entered" );
46
}
47
} // end class ClassAverage
Enter grade or -1 to quit: 97
Enter grade or -1 to quit: 88
Enter grade or -1 to quit: 72
Enter grade or -1 to quit: -1
Total of the 3 grades entered is 257
Class average is 85.67
Fig. 4.10 | Solving the class-average problem using sentinel-controlled repetition. (Part 2 of 2.)
Search WWH ::




Custom Search