In my program I have subjects and each subject can have many assignments. I am trying to find the average grade of each assignment where "assignmentGradeAchieved" is not null.
In an array I have stored these assignmentGradeAchieved. I want to find the average result (adding each number together then dividing by the number of items) However it isn't displaying the correct arraysize. It is displaying it as 1 when it should be 2. Here is the line of code where I try to find the arraysize: arraySize = (assignmentGradesAchieved.size());
//For each assignment belonging to the subject, if AssignmentGradeAchieved is not null then add AssignmentGradeAchieved to an arraylist called AssignmentGradesAchieved. //If a subject has more than one assignments that have AssignmentGradeAchieved then more than one AssignmentGradeAchieved should be added to the arryalist called AssignmentGradesAchieved. Therefore the size of the array should be more than one. //one of my subjects has two assignments both with AssignmentGradeAchieved so the array size should be 2 not 1
for(int i=0; i<subjects.size(); i++){ //for each subject in the list
Subject subject = subjects.get(i);
List<Assignment> assignments = subject.getAssignment(); //Get the list of assignments belonging to current subject
for(int y=0; y<assignments.size(); y++ ) { //For each assignment in the list
Assignment assignment = assignments.get(y);
ArrayList<Double> assignmentGradesAchieved = new ArrayList<Double>();
if(assignments.get(y).getAssignmentGradeAchieved()!=null) {
assignmentGradesAchieved.add(assignments.get(y).getAssignmentGradeAchieved());
arraySize = 0;
arraySize = (assignmentGradesAchieved.size());
for(int z=0; z<assignmentGradesAchieved.size(); z++) {
arraySize = 0;
allAssignments = allAssignments + assignmentGradesAchieved.get(z);
arraySize = (assignmentGradesAchieved.size());
averageAssignGrade = (allAssignments / arraySize);
}
}
}
}
THE SOLUTION:
for(int i=0; i<subjects.size(); i++){ //for each subject in the list
Subject subject = subjects.get(i);
List<Assignment> assignments = subject.getAssignment(); //Get the list of assignments belonging to current subject
ArrayList<Double> assignmentGradesAchieved = new ArrayList<Double>();
for(int y=0; y<assignments.size(); y++ ) { //For each assignment in the list
Assignment assignment = assignments.get(y);
allAssignments =0;
if(assignments.get(y).getAssignmentGradeAchieved()!=null) {
assignmentGradesAchieved.add(assignments.get(y).getAssignmentGradeAchieved());
for(int z=0; z<assignmentGradesAchieved.size(); z++) {
allAssignments = allAssignments + assignmentGradesAchieved.get(z);
}
}
}
arraySize = 0;
arraySize = (assignmentGradesAchieved.size());
averageAssignGrade = (allAssignments / arraySize);
}
assignmentGradesAchieved.add