1

I am trying to create a method which calculates the total sum of all the elements in array scores. When I compile this I get a "Variable may not have been initialized error" even though I've already declared it within the method

public double getTotal() {
        double total;
        for(int i=0;i<scores.length;i=i+2) {
            total = scores[i] + scores[i+1];
            
        }
        
        return total;
    }

1 Answers1

4

Yes you have declared it, but you didn't make sure to initialize it. What would happen if scores.length == 0? Then you would try to return total, which is null at this point.

If you are trying to sum up the contents of your scores, then it should probably look something like this:

public double getTotal() {
    double total = 0.0;
    for(int i = 0; i < scores.length; i++) {
        total += scores[i];    
    }
    return total;
}
maloomeister
  • 2,461
  • 1
  • 12
  • 21