0

I have this program and its output:

    import java.util.Random;
    public class Grades {
    public static void main(String[] args) {
    Random random = new Random();
    int grades[][][] = new int[10][5][3];
    int i,j,k;
    int l;        

    System.out.println("\nGrades of all students in 3 subjects and their average:\n");
    for(i=0;i<10;i++)
    {
    for(j=0;j<5;j++)
    {
    int sum = 0;
    int ave = 0;
    System.out.print("{");
    for(k=0;k<3;k++)
    {
    l = random.nextInt(40)+60;
    grades[i][j][k] = l;
    sum += grades[i][j][k];
    ave = sum/3;
    System.out.print(l+",");
    }                                               
    System.out.print("}= "+ave);                
    }
    System.out.println();
    }
    }
    }

output:

Grades of all students in 3 subjects and their average:

  {80,83,75,}= 79{75,85,93,}= 84{93,91,76,}= 86{71,93,96,}= 86{60,60,67,}= 62
  {60,74,73,}= 69{85,87,93,}= 88{88,76,83,}= 82{80,96,95,}= 90{68,78,84,}= 76
  {77,87,85,}= 83{78,65,94,}= 79{72,88,78,}= 79{86,80,87,}= 84{81,85,94,}= 86
  {69,78,75,}= 74{71,97,91,}= 86{92,81,69,}= 80{89,62,85,}= 78{68,80,70,}= 72
  {82,70,98,}= 83{65,73,65,}= 67{96,90,96,}= 94{86,88,79,}= 84{94,77,96,}= 89
  {64,93,85,}= 80{69,93,69,}= 77{76,68,67,}= 70{60,88,97,}= 81{83,68,96,}= 82
  {78,94,77,}= 83{97,83,81,}= 87{90,81,92,}= 87{65,88,98,}= 83{96,92,79,}= 89
  {75,61,76,}= 70{61,73,89,}= 74{88,96,77,}= 87{60,64,82,}= 68{74,73,85,}= 77
  {98,70,99,}= 89{90,76,67,}= 77{84,99,90,}= 91{96,97,97,}= 96{99,72,73,}= 81
  {80,98,71,}= 83{84,93,99,}= 92{77,97,78,}= 84{94,96,95,}= 95{80,77,66,}= 74

the program will calculate the average of every 3 values of the 3 dimensional array. And I want to sort these calculated values and I have no idea how to do it. I am new to java. Can anyone help me with this?

1 Answers1

1

This looks like a homework question, so you get hints instead of code.

  • Make a Grade class to hold your grades and their average that implements java.lang.Comparable (and has a compareTo method).
  • Make an array of Grade objects: Grade[] grades
  • Use Arrays.sort(grades) to sort them.

For more flexible sorting options, look at java.util.Comparator.

You could also look at using a java.util.TreeSet but you would have to add something like a student id so each element in the set is unique.

edoloughlin
  • 5,821
  • 4
  • 32
  • 61