0

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

6
  • 3
    Aren't you getting some error because of w <= allSwithces.size() in your inner for loop? Some kind of IndexOutOfBounds maybe? No? Commented Jul 1, 2015 at 1:14
  • Have you tried to remove the continue statements? Commented Jul 1, 2015 at 1:14
  • 2
    both of those continue statements are not inside of a conditional block, so they're definitely going to be hit on the first loop every time. continue doesn't mean "do the next iteration of the loop", it means "stop this loop and continue at the next instruction after the loop" Commented Jul 1, 2015 at 1:15
  • Have you tried putting the continue inside the if ? Commented Jul 1, 2015 at 1:15
  • 2
    @Gus I think you have break and continue mixed up. for(int i=0; i<10; i++) {System.out.println(i);continue;} will output 0 through 9. Commented Jul 1, 2015 at 1:20

1 Answer 1

5
  1. Outer loop is terminating because inner loop is throwing an 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.

  1. You are not breaking in the inner loop. Just comment says that it should break but code doesn't.

  2. You continues 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.

Sign up to request clarification or add additional context in comments.

2 Comments

the problem now is, after ending the loop, it doesn’t complete the rest of the code in the function :|
What do you mean? What is the output and what is the code? And again, you can accept the answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.