2016-01-11 44 views
1

我对for循环中的某些内容感到陌生。如果我调用setCurrentId(1),则generateid将返回0(返回语句在for循环内执行)。再次,如果我与setCurrentId(2)调用它返回0(返回语句执行外循环),这是不应该的。不执行for循环中的第二个条件

我有一个配置文件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 

回答

0

AppController.getInstance().getProfile().get(i).getId() == profile_id可能是为第一档项虚假这样你就不会步入循环并返回0。

for循环中的条件意味着'do when true',因此循环体被跳过。

+0

编号第一个配置文件项目已成功从内部for循环中返回,其中i为0.我已使用日志对其进行了检查。 – Patriotic

+0

是的。但检查它''profile_id = 2'。 for(i = 0; i skyman

+0

我也检查过它。当我= 1然后profile_id == 2。所以,它应该执行,但它执行时,我使用if语句。 – Patriotic

1

您在For循环中的条件是AND(& &)。第一个循环查找的条件是真实的迭代,因为它是假的,它省略了循环。

对于for循环中的任何多个条件,迭代只能使用True功能。在你的第二个代码片段循环条件是真的,直到我配置文件列表的大小和因此循环被触发。

@skyman语句for循环中的条件意味着'do when true',所以循环体被跳过。这是正确的。

实时查看第二个代码段是个好习惯。原因是异常处理。另外,我在你的代码片段中看到惯例并不仅仅用于你的参考。 Java Conventions

相关问题