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