Reputation: 67
for loop in below java code stop in the first iteration, I don’t know why! can you help me?
controllerSwitches elements is { 1, 2}
allSwithces elements is {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;
}
it gets the first p index and compare it with all element of allSwitches list, then its break the loop. I mean it doesn’t go to the second p index. the output is
1 1
1 2
1 3
1 4
it does not compare the second element of controllerSwitches with allSwithces elements
Upvotes: 0
Views: 2069
Reputation: 2984
IndexOutOfBoundException
at the end of the comparison.Change
for ( int w = 0; w <= allSwithces.size() ; w++)
to
for ( int w = 0; w < allSwithces.size() ; w++)
and all combinations will be printed.
You are not breaking in the inner loop. Just comment says that it should break but code doesn't.
You continue
s are redundant as code will automatically continue. Remove them.
Additionally, putting complete code would have helped as you definitely would have received an exception in the caller.
Upvotes: 5