下面的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元素进行比较
最佳答案
- 外部循环正在终止,因为内部循环在比较结束时抛出
IndexOutOfBoundException
。
改变
for ( int w = 0; w <= allSwithces.size() ; w++)
到
for ( int w = 0; w < allSwithces.size() ; w++)
所有组合都将被打印。
您没有中断内部循环。只是评论说它应该中断,但代码不会。
您的
继续
是多余的,因为代码会自动继续。删除它们。
此外,放置完整的代码会有帮助,因为您肯定会在调用者中收到异常。
关于java - for 循环在第一次迭代中停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31151031/