Java Reference
In-Depth Information
outFile.println();
//Line 51
if (count != 0)
//Line 52
outFile.printf("Class Average: %.2f %n",
sum / count);
//Line 53
else
//Line 54
outFile.println("No data.");
//Line 55
outFile.close();
//Line 56
}
//Line 57
}
//Line 58
Sample Run:
Input File:
Steve Gill 89
Rita Johnson 91.5
Randy Brown 85.5
Seema Arora 76.5
Samir Mann 73
Samantha McCoy 88.5
Output File:
Steve
Gill
89.00 B
Rita
Johnson
91.50 A
Randy
Brown
85.50 B
Seema
Arora
76.50 C
Samir
Mann
73.00 C
Samantha
McCoy
88.50 B
Class Average: 84.00
The preceding program works as follows. The statements in Lines 7 to 11 declare variables
required by the program. The statements in Lines 12 and 13 initialize the variables sum and
count . The statement in Line 14 declares inFile to be a reference variable of type Scanner
and associates it with the input file. The statement in Line 15 declares outFile to be a
reference variable of type PrintWriter and associates it with the output file.
The while loop from Lines 16 to 50 reads each student's first name, last name, and test
score, and outputs the name followed by the test score and grade. Specifically, the
statement in Line 18 reads the first name, the statement in Line 19 reads the last name,
and the statement in Line 20 reads the test score. The statement in Line 21 updates the
value of sum . (After reading all the data, the value of sum stores the sum of all the test
scores.) The statement in Line 22 updates the value of count . (The variable count stores
the number of students in the class.) The switch statement from Lines 23 to 48
determines the grade from testScore and stores it in the variable grade . The statement
in Line 49 outputs a student's first name, last name, test score, and grade.
The if ... else statement in Lines 52 to 55 outputs the class average, and the statement
in Line 56 closes the file associated with outFile , which is stData.out .
Search WWH ::




Custom Search