// Solution to CS 111A in-class exercise 6 by Tony Huang
import java.util.Scanner;
public class JaggedAverage
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int numCourses, numTests;
double[][] testScores;
double [] sumArray;
double highScore;
System.out.print("How many courses are you taking? ");
numCourses = s.nextInt();
testScores = new double[numCourses][]; // allocate an array of references to 1-D arrays (rows)
sumArray = new double[numCourses];// -Edit-
for(int i = 0; i < numCourses; i++)
{
System.out.print("How many tests are in course number "
+ (i+1) + "? ");
numTests = s.nextInt();
testScores[i] = new double[numTests]; // allocate this row: a 1-D array of doubles
}
for(int courseId=0; courseId < testScores.length; courseId++)
for(int testId=0; testId < testScores[courseId].length; testId++)
{
System.out.print("What was your grade on test "
+ (testId+1) + " for course "
+ (courseId+1) + "? ");
testScores[courseId][testId] = s.nextDouble();
sumArray[courseId] += testScores[courseId][testId]; // -Edit-
}
for(int count = 0; count < testScores.length; count++) //-Edit-
{
sumArray[count] = (sumArray[count])/(testScores[count].length);
}
highScore = 0; // -Edit-
for(int sumCountIndex = 0; sumCountIndex < testScores.length; sumCountIndex++)// -Edit-
{
System.out.println("The average for course " + (sumCountIndex+1) + " is " + sumArray[sumCountIndex]);// -Edit-
if(highScore < sumArray[sumCountIndex])
{
highScore = sumArray[sumCountIndex];
}
}
System.out.println("The highest average score is " + highScore);// -Edit-
}
}
/* Sample Output:
How many courses are you taking? 2
How many tests are in course number 1? 4
How many tests are in course number 2? 3
What was your grade on test 1 for course 1? 10
What was your grade on test 2 for course 1? 20
What was your grade on test 3 for course 1? 30
What was your grade on test 4 for course 1? 40
What was your grade on test 1 for course 2? 90
What was your grade on test 2 for course 2? 100
What was your grade on test 3 for course 2? 85
The average for course 1 is 25.0
The average for course 2 is 91.66666666666667
The highest average score is 91.66666666666667
*/
syntax highlighted by Code2HTML, v. 0.9