-1

I have the following method:

public static List<Integer> gradingStudents(List<Integer> grades) {
    for(int i = 0; i < grades.size(); i++){
        if(grades.get(i) < 40)
            continue;
        else if(grades.get(i) % 5 < 3)
            grades.get(i) = grades.get(i) + (Math.abs(grades.get(i)%5-5));     
        else
            continue;
    }
    return grades;
}

I get an unexpected type error at else if part. Why can't I change the element of grades, like I wrote in the code, above?

Abra
  • 19,142
  • 7
  • 29
  • 41

2 Answers2

8

You cannot assign to grades.get(i).

I suggest you simplify your code as follows:

public static List<Integer> gradingStudents(List<Integer> grades) {
    for(int i = 0; i < grades.size(); i++){
        int grade = grades.get(i);
        if (grade >= 40 && grade % 5 < 3) {
            grades.set(i, grade + Math.abs(grade%5-5));   
        }  
    }
    return grades;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

It is because you are trying to modify the list like how you try to modify a list or dict in python as shown here. You have to use the inbuilt method .set() or .get(). set is used to add element by replacing it in the given index, add method adds the element to given index by pushing rest of the elements. You can understand more about the set and get method here

To this particular problem, as @Eran mentioned here, you can use the .set() method.