-1

I have two for loops and in the innermost for loop I have a switch. And is it possible that in one case of the switch, the entire trip through the outermost loop should be aborted, so that one goes over to the next value automatically, for example, the outermost loop is at the 1 pass and with the command in the switch, I come to the second pass, is that possible?

With break it will not work, do you have any ideas?

example:

for (){
  for (){
    switch(){
    case 1:
    //now I want to break here the inner loop, to go 1 step further, by the outer loop
    }
  }
  // do something not wanted in case 1
}
greybeard
  • 2,249
  • 8
  • 30
  • 66
kekbaui
  • 3
  • 1
  • 1
    Label the loop from which you want to break, and use a break-with-label (a.k.a. a "labelled break"). – John Bollinger Mar 17 '22 at 22:08
  • Note: you seem to be getting your "inner" and "outer" mixed up. In the code presented, the `switch` statement is inside the *inner* (which is also inner*most*) loop, and I suspect from your description that it is that loop, not the outer one, from which you want to break. – John Bollinger Mar 17 '22 at 22:13
  • thank you all, i didnot know, that we can use labels! – kekbaui Mar 17 '22 at 22:15
  • 1
    A labelled break is one option. When I encounter this kind of thing though, I prefer to refactor the whole lot into a new method, and use `return`. – Dawood ibn Kareem Mar 17 '22 at 22:16
  • (@Ivar: not quite, I guess. The trick here is to continue an outer loop from the top.) – greybeard Mar 18 '22 at 07:05

2 Answers2

2

As I am not certain exactly what you consider first I labelled both. The following will continue the next iteration of the outer loop.

outer:
for () {
   inner:
   for () {
       switch() {
       case 1:
         continue outer;  // or break inner;
       }
   }
}

Note that the in the case of break inner;, the label must be still be included since break; would simply break out of the switch block.

WJS
  • 36,363
  • 4
  • 24
  • 39
0

you can use label:

first :for (int i = 0; i < args.length; i++) {
    second : for (int j = 0; j < args.length; j++) {
        switch (j) {
        case 1:

            break second;// use this for breaking the second loop or use 
            //continue first; // to break the second and continue the first
        default:
            break;
        }
    }
}
Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35