Java Reference
In-Depth Information
EXAMPLE 5-7
The following code uses an EOF-controlled
while
loop to find the sum of a set of
numbers:
static
Scanner console =
new
Scanner(System.in);
int
sum = 0;
int
num;
while
(console.hasNext())
{
num = console.nextInt();
//Get the next number
sum = sum + num;
//Add the number to sum
}
System.out.printf("Sum = %d%n", sum);
EXAMPLE 5-8
Suppose we are given a file consisting of students' names and their test scores, a number
between 0 and 100 (inclusive). Each line in the file consists of a student name followed by
the test score. We want a program that outputs each student's name followed by the test
score and the grade. The program also needs to output the average test score for the class.
Consider the following program.
// This program reads data from a file consisting of students'
// names and their test scores. The program outputs each
// student's name followed by the test score and the grade. The
// program also outputs the average test score for all students.
import
java.io.*;
//Line 1
import
java.util.*;
//Line 2
public class
ClassAverage
//Line 3
{
//Line 4
public static void
main(String[] args)
throws
FileNotFoundException
//Line 5
{
//Line 6
String firstName;
//Line 7
String lastName;
//Line 8
double
testScore;
//Line 9
char
grade = '';
//Line 10
double
classAverage;
//Line 11
double
sum = 0;
//Line 12
int
count = 0;
//Line 13
Search WWH ::
Custom Search