Reputation: 2191
I have a method public int bar()
, where i have declared an int total
(in the method body ofc). So this should be a simpel local variable, the thing is that eclipse complain about
Description Resource Path Location Type
The local variable total may not have been initialized Repository.java /proj_individual/src/repo line 35 Java Problem
general example :
public int foo(){
int total;
for(... : ...){
total += 1; // complains
}
return total;// complains
}
and my exact code:
public int getLocatars(){
int total;
for ( Map.Entry<Apartment, List<Expense>> entry : dic.entrySet() ) {
if(entry.getKey().isDebt()){
total += entry.getKey().getNrProple();
}
}
return total;
}
I have no idea what I may have done wrong, so any idea is helpful, thank you.
Upvotes: 2
Views: 136
Reputation: 47367
Change it from:
int total;
to:
int total = 0;
For better understanding, see: differences between declaration and initialization.
Upvotes: 4
Reputation: 1503649
Your variable isn't definitely assigned a value, so you can't read it.
Imagine if your entry set is empty, or has no debt
entries... what value would you want to return?
More than that, even if it does get into the inner-most part of your loop, what initial value would you expect to be added to?
Unlike static and instance fields, local variables don't have default values: you have to assign values to them before you read them. I suspect you just want:
int total = 0;
Upvotes: 6