In: Computer Science
JAVA: This is my code, but when it runs, for the "Average Score" output, it only gives me NaN. How can I fix that?
import java.util.Scanner;
public class prog4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String name;
double score;
double minScore = 0;
double maxScore = 0;
int numberOfRecords = 0;
double sum = 0;
double average = sum / numberOfRecords;
System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name",
"Score");
while (reader.hasNext()) {
name = reader.next();
score = reader.nextDouble();
sum += score;
System.out.printf("%8d%12s %16.2f\n", numberOfRecords + 1, name,
score);
if (numberOfRecords == 0) {
minScore = score;
} else if (minScore > score) {
minScore = score;
}
if (maxScore < score) {
maxScore = score;
}
numberOfRecords += 1;
}
System.out.println("Number of Records: " +
numberOfRecords);
System.out.printf("Max Score: %.2f\n", maxScore);
System.out.printf("Min Score: %.2f\n", minScore);
System.out.printf("Average Scores: %.2f\n", average);
}
}
Problem is with that average is being calculated before reading and processing scores. There is a need of change at two lines of code.
Modified lines are highlighted using BOLD case.
Update Program:
import java.util.Scanner;
public class prog4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String name;
double score;
double minScore =
0;
double maxScore =
0;
int numberOfRecords =
0;
double sum = 0;
double
average;
System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name",
"Score");
while (reader.hasNext())
{
name = reader.next();
score = reader.nextDouble();
sum += score;
System.out.printf("%8d%12s %16.2f\n", numberOfRecords + 1, name,
score);
if (numberOfRecords == 0) {
minScore = score;
} else if (minScore > score) {
minScore = score;
}
if (maxScore < score) {
maxScore = score;
}
numberOfRecords += 1;
}
average = sum /
numberOfRecords;
System.out.println("Number of Records: " + numberOfRecords);
System.out.printf("Max
Score: %.2f\n", maxScore);
System.out.printf("Min
Score: %.2f\n", minScore);
System.out.printf("Average Scores: %.2f\n", average);
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output: