【问题标题】:not executing second condition in for loop不执行 for 循环中的第二个条件
【发布时间】: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

【问题讨论】:

    标签: java android


    【解决方案1】:

    你在 For 循环中的条件是 AND (&&)。第一个循环寻找条件为真以进行迭代,并且由于条件为假,它省略了循环。

    对于 for 循环中的任何多个条件,只有 True 功能才可能进行迭代。在您的第二个代码中,sn-p 循环条件为真,直到 i

    @skyman 语句 for 循环中的条件表示“当为真时执行”,因此跳过循环体。这是正确的。

    实时查看第二个代码 sn-p 是一种很好的做法。原因是异常处理。另外,我在您的代码中看到 sn-p 约定不仅仅用于您的参考。Java Conventions

    【讨论】:

      【解决方案2】:

      AppController.getInstance().getProfile().get(i).getId() == profile_id 对于第一个配置文件项可能为 false,因此您不会进入循环并返回 0。

      for 循环中的条件表示“为真时执行”,因此跳过循环体。

      【讨论】:

      • 没有。第一个配置文件项从 for 循环内部成功返回,其中 i 为 0。我已使用日志对其进行检查。
      • 是的。但请检查profile_id = 2。 for (i = 0; i
      • 我也查过了。当 i=1 然后 profile_id == 2 。所以,它应该执行,但是当我使用 if 语句时它会执行。
      猜你喜欢
      • 2013-12-12
      • 2019-06-27
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多