我有一个方法public int bar(),我已经声明了一个int total(在方法体中ofc).所以这应该是一个简单的局部变量,那就是eclipse抱怨的
Description Resource Path Location Type
The local variable total may not have been initialized Repository.java /proj_individual/src/repo line 35 Java Problem
Run Code Online (Sandbox Code Playgroud)
一般例子:
public int foo(){
int total;
for(... : ...){
total += 1; // complains
}
return total;// complains
}
Run Code Online (Sandbox Code Playgroud)
和我的确切代码:
public int getLocatars(){
int total;
for ( Map.Entry<Apartment, List<Expense>> entry : dic.entrySet() ) {
if(entry.getKey().isDebt()){
total += entry.getKey().getNrProple();
}
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么,所以任何想法都有帮助,谢谢.
您的变量未明确赋值,因此您无法读取它.
想象一下,如果您的输入集是空的,或者没有debt条目......您想要返回什么值?
更重要的是,即使它确实进入了循环的最内部,你期望添加到什么初始值?
与静态和实例字段不同,局部变量没有默认值:您必须在读取它们之前为它们赋值.我怀疑你只想要:
int total = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |