I have a question regarding the for-loop and ArrayList. I have a HashMap with String and Integers, where the String represents a class, and the Integer represents the grade. They I have a collection of students in an ArrayList. So what I am trying to do is find the average of the grades of the students in the ArrayList. This is the code of that class:
import java.util.ArrayList;
public class BachelorStudenter {
private ArrayList<BachelorStudent> bs;
public Bachelorstudenter() {
bs = new ArrayList<>();
}
public int bsGjennomsnitt() {
int sum = 0;
int gjennomsnitt = 0;
if(!bs.isEmpty()){
for(BachelorStudent b : bs.values){
sum += b.finnGjennomsnitt();
}
return gjennomsnitt;
}else {
return 6;
}
}
}
I know that the bs.values in the for-loop within the if-statement is wrong, but I've tried googling what I should use instead, and neither .contains or .size works.
Oh, and I also have another class called BachelorStudent, where I can create an object of the BachelorStudent and it will be put in the ArrayList in Bachelorstudenter.
Does anyone know what I need to put there instead?
If what you want to to is to return the average of the average grade over all the students you could do the following:
import java.util.ArrayList;
public class Bachelorstudenter {
private ArrayList<Bachelorstudent> bs;
public Bachelorstudenter() {
bs = new ArrayList<>();
}
public double bsGjennomsnitt() {
double sum = 0.0;
double gjennomsnitt = 6.0;
if(!bs.isEmpty()){
for(Bachelorstudent b : bs){
sum += b.finnGjennomsnitt();
}
gjennomsnitt = sum/bs.size()
}
return gjennomsnitt;
}
}
please note that I changed the return value
, sum
and gjennomsnitt
to double
as an average may also be a non-integer value.
The answer also assumes that the b.finnGjennomsnitt()
returns the average over all classes a student attends and returns this. If you only want to return the average for all students in ONE class the answer will not give you this. Please specify in your question and also include the code for finnGjennomsnitt()
if this is part of the question.
The method in the answer will return 6.0 as average if there are no students, as in the code in the question. Perhaps this should be reconsidered as it makes the case of an exceptional group of students with straight 6.0 grades equal to the case of no students. Perhaps you can return -1 when there are no students?