1. Member
Join Date
Mar 2008
Posts
3
Rep Power
0

## Calculate Average

Can someone please tell me why my averages are coming up as 0s?

Java Code:
```import java.io.*;
import java.util.*;

public class AverageScores
{
public static void main (String[] args)
throws FileNotFoundException

{
double test1, test2, test3, test4, test5;
String name;
double average = 0.0;

Scanner inFile = new Scanner(new FileReader("student_scores.txt"));

PrintWriter outFile = new PrintWriter("student_scores.out");

outFile.println("Student    Test1 Test2 Test3 Test4 Test5 Average Grade");

while (inFile.hasNext())
{
name = inFile.next();
test1 = inFile.nextDouble();
test2 = inFile.nextDouble();
test3 = inFile.nextDouble();
test4 = inFile.nextDouble();
test5 = inFile.nextDouble();
calculateAverage(average, test1, test2, test3, test4, test5);

outFile.printf("%-9s %5.0f %5.0f %5.0f %5.0f %5.0f %5.0f %n",
name, test1, test2, test3, test4, test5, average);

}

inFile.close();
outFile.close();
}

public static void calculateAverage(double a, double t1, double t2, double t3, double t4, double t5)

{
a = (t1 + t2 + t3 + t4 + t5) / 5.0;
}
}```

2. Member
Join Date
Mar 2008
Posts
3
Rep Power
0
And just so everyone knows, calculateAverage needs to be a viod method, not a return method.

3. Your calculateAverage method must be a double so that it could return a double value that will be assigned to average variable to be able to show the expected results,

eg.

average = calculateAverage(parameters);

This is intended for the guests who browse this thread for additional clarification.
Last edited by sukatoa; 06-12-2008 at 05:43 PM.

4. Why are we using printf() ~ that looks like something that was in the original spec as a design the instructor likes. Class Double will have a toString() method, as will the Sting class being able to take a double, likely at least and I would think so.

As you have it, calculate average may be declared as sukatoa shows and as well should have a counter of some kind, this avoids the nasty (1,2,3,4,5,6,7,8,9,0) parameter list style and lends to the loop style which your problem domain is natural.

We then are presented with the matter of passing the list, since this is obviously a learning exercise I suggest you consider how the list could be passed to the calc()

Skip worrying about how to do that with a file, there are coding constructs that will do this.
Last edited by Nicholas Jordan; 06-12-2008 at 08:47 PM. Reason: fix spelling of domain

5. That's much better.

The most better way I think is while read each double value, update the total of all. Then you comes with a single value(a double) to find the average.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•