简体   繁体   中英

Finding the average of numbers in an array

I have an array of test grades for each student in a class. As an example, for Adam test1=90 test2=92 test3=93 , so the average would be 91.67 . I would then save this as Array6 . Then using that array, I would take 30% of that plus 70% of the final ( array5 ) to make new array courseaverage .

I have tried to implement this in my code below, but it doesn't work correctly. Could anyone please suggest the problem...

public class Proj5 {
    public static void main (String[] args) {        
        String[] Array1 = {new String ("Adam"),new String ("Smith"),new String ("Jones"),new String ("Becky"),new String ("Taylor")};       
        Integer[] Array2 = {new Integer(90),new Integer(89),new Integer(86),new Integer(76),new Integer(95)};        
        Integer[] Array3 = {new Integer(92),new Integer(79),new Integer(85),new Integer(90),new Integer(87)};
        Integer[] Array4 = {new Integer(93),new Integer(80),new Integer(90),new Integer(87),new Integer(92)};
        Integer[] Array5 = {new Integer(90),new Integer(77),new Integer(86),new Integer(92),new Integer(89)};

        System.out.println("Name Test1 Test2 Test3 Final Average Grade");

        for (int column = 0; column<Array1.length; column++){
            System.out.printf("%s ", Array1[column]);
            System.out.printf("%s   ", Array2[column]);
            System.out.printf("%s    ", Array3[column]);
            System.out.printf("%s    ", Array4[column]);
            System.out.printf("%s  ", Array5[column]);
            System.out.println(); //start new line of output
        }
    }
}

An array does not have a get() method but an ArrayList does so if you change your arrays to ArrayLists then you can use get() to retrieve the value.

If I understand correctly you have an array that holds the names of each student and each student's grades are held in a seperate array for each student?

String[] students= {"Adam","Smith","Jones"}; 
int[] adamGrades = {90,92,93};
double gradesTotal = 0.00;
for(int i=0; i < adamGrades.length; i++){
  gradesTotal += adamGrades[i];
}
double avg = (gradesTotal/adamGrades.length);
System.out.print(avg);

That would give you the average for "Adam" and you should be able to use that to figure out the rest of your problem.

To not give away the exact answer (since this is homework) you need to take the array, add up all the elements and divide that sum by the number of elements in the array. This could be done easily in a function call accepting the array and returning the average.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM