【问题标题】:for loop stop in the first iteration在第一次迭代中 for 循环停止
【发布时间】:2015-07-01 01:12:00
【问题描述】:

java代码下面的for循环在第一次迭代中停止,我不知道为什么! 你能帮帮我吗?

controllerSwitches 元素为 { 1, 2}

allSwithces 元素是 {1,2,3,4}

for (int p = 0; p < controllerSwitches.length; p++) 
{  
    switches tempSwitch = controllerSwitches[p];
    for (int w = 0; w <= allSwithces.size(); w++)
    {
        System.out.println(tempSwitch.getSwitchId() +"\t" + allSwithces.get(w).getSwitchId());
        if (allSwithces.get(w).getSwitchId().equals(tempSwitch.getSwitchId())) 
        { 
            failedControllerswitches.add(allSwithces.get(w)); // it is break after getting the first p index  
        }
        continue;
    }
    continue;
}

它获取第一个 p 索引并将其与 allSwitches 列表的所有元素进行比较,然后打破循环。我的意思是它不会进入第二个 p 索引。 输出是

1 1

1 2

1 3

1 4

它不会将 controllerSwitches 的第二个元素与 allSwithces 元素进行比较

【问题讨论】:

  • 你是不是因为你的内部 for 循环中的w &lt;= allSwithces.size() 而得到一些错误?某种 IndexOutOfBounds 可能吗?没有?
  • 您是否尝试删除continue 语句?
  • 这两个continue 语句都不在条件块内,因此每次都肯定会在第一个循环中被命中。 continue 并不是说​​“进行循环的下一次迭代”,而是表示“停止这个循环并在循环之后的下一条指令处继续”
  • 你试过把 continue 放在 if 里面吗?
  • @Gus 我想你把breakcontinue 搞混了。 for(int i=0; i&lt;10; i++) {System.out.println(i);continue;} 将输出 0 到 9。

标签: java arrays list for-loop


【解决方案1】:
  1. 外循环正在终止,因为内循环在比较结束时抛出了 IndexOutOfBoundException

改变

        for ( int w = 0; w <= allSwithces.size() ; w++)

        for ( int w = 0; w < allSwithces.size() ; w++)

所有的组合都会被打印出来。

  1. 您没有中断内部循环。只是评论说它应该中断,但代码不会。

  2. continues 是多余的,因为代码会自动继续。删除它们。

此外,放置完整的代码会有所帮助,因为您肯定会在调用者中收到异常。

【讨论】:

  • 没问题。接受答案,可能吗? ;)
  • 现在的问题是,在结束循环后,它并没有完成函数中的其余代码:|
  • 什么意思?输出是什么,代码是什么?再次,您可以接受答案!