so this program takes an input file and computes the class average and lists the students who are below average and the students with the highest score. Heres what im having trouble with:

Having trouble getting the proper for loop to calculate sum, I've tried many different ways but its not getting the correct average.

also, do the loops for finding the highest score, and listing the students below average and with the highest scores look correct?

thanks a lot!

import java.io.*;
import java.util.*;

public class ClassInfo {

	public static void main(String[] args) {
		
		//declare variables 
		final int MAX_SIZE = 50;
		String[] firstname = new String[MAX_SIZE];
		String[] lastname = new String[MAX_SIZE];
		int[] scores = new int[MAX_SIZE];
		int size = 0, highest;
		double sum = 0.0, average = 0.0;
		Scanner inFile = null;
		//PrintWriter outFile = null;
		
		try {
			inFile = new Scanner(new FileReader("input.txt"));
			//outFile = new PrintWriter("output.txt");
		}
		catch(Exception e){
			System.out.println("File not found");
			System.exit(1);
		}
		
		
		while (inFile.hasNext()) {
			firstname[size] = inFile.next(); 
			lastname[size] = inFile.next();
			scores[size] = inFile.nextInt(); 
			size++;
		}
		
		//compute the sum of all scores
		for (int i=0; i < size; i++) {
			sum += i++; // add to sum, scores[i]
		}
		
		//compute and display average 
		average = sum/9.0;
		System.out.println("The class average is : " + average); 
		
		//compute highest score
		highest = scores[0]; 
		for (int i=1; i < size; i++) {
			if (scores[i] > highest); 
			scores[i] = highest;
		}
		
		//list the student that are below average
		System.out.println("Students with below average scores are:\n");
		for (int i=0; i<size; i++) {
			if (scores[i] < average);
			System.out.println(firstname[i] + " " + lastname[i]);
		}
		
		//list the students with highest score
		System.out.println("Students with highest score are:\n");
		for (int i=0; i<size; i++) {
			if (scores[i] == highest);
			System.out.println(firstname[i] + " " + lastname[i]);
		}

	}

}
for (int i=0; i < size; i++) {
sum += scores[i]; 
}

Try that. The variable "i" is already incremented automatically because you put "i++" in the for loop. You need to index your scores array at every index. So the above loop will do that.

Try something like this:

for(int i = 0; i < size; i++ )
{
  sum = sum + scores[i];
}

Except replace the scores part with the name of your array. That should do it for that part. Your if statements don't need the ; after that line. The lowest mark and highest mark code looks ok to me. If you could attach the file to be read then I'd create the whole code, mainly for my own java practice. But I wouldn't post it all :P

This article has been dead for over six months. Start a new discussion instead.