【发布时间】:2016-01-12 07:32:50
【问题描述】:
我对 for 循环中的某些内容感到奇怪。如果我调用 setCurrentId(1) 则 generateid 将返回 0(return 语句在 for 循环内执行)。同样,如果我用 setCurrentId(2) 调用它会返回 0(返回语句在循环外执行),这是不应该的。
我有一个之前创建的配置文件 ArrayList,ID 为 1,2,3,4。所以我现在用这些 id 检查一个随机 id。但在 for 循环中它只执行第一次。
public void setCurrentId(int id) {
Log.d("status scd :", "scI a " + id);
this.current_id = GenerateId(id);
Log.d("status scd :", "scI b " + this.current_id);
}
public int GenerateId(int profile_id) {
if (AppController.getInstance().getProfile() != null) {
Log.d("status scd :", "GI ");
for (int i = 0; i < AppController.getInstance().getProfile().size() && AppController.getInstance().getProfile().get(i).getId() == profile_id; i++) {
return i;
}
}
return 0;
}
日志结果是:
status scd :: scI a 1
status scd :: GI
status scd :: scI b 0
status scd :: scI a 2
status scd :: GI
status scd :: scI b 0
所以,我调试并发现在第一次调用 setCurrentId() 后第二个条件没有执行。
当我将第二个条件放在里面时,如果它工作正常。但是不知道为什么会这样。所以,我很想弄清楚。
这里是更正的代码:
public void setCurrentId(int id) {
Log.d("status scd :", "scI a " + id);
this.current_id = GenerateId(id);
Log.d("status scd :", "scI b " + this.current_id);
}
public int GenerateId(int profile_id) {
if (AppController.getInstance().getProfile() != null) {
Log.d("status scd :", "GI ");
for (int i = 0; i < AppController.getInstance().getProfile().size(); i++) {
if (AppController.getInstance().getProfile().get(i).getId() == profile_id) {
return i;
}
}
}
return 0;
}
还有日志结果:
status scd :: scI a 1
status scd :: GI
status scd :: scI b 0
status scd :: scI a 2
status scd :: GI
status scd :: scI b 1
【问题讨论】: