Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

Break can not be used out side of loop

for(int i = 0; i < 10; ++i) {
  outerTimer = new Timer() {
    @Override
    public void run() {        
      if(stopTimer) {
        cancel();
        break; // break cannot be used outside of a loop or a switch
      }

     repeatLoop();
    }         
  };

  outerTimer.run();
  outerTimer.scheduleRepeating(tmptimerDuration);
}

In the above code I used break to break the loop when stoptimer is true but it throws an error

break cannot be used outside of a loop or a switch 

But I used this break inside of timer where timer inside of another for loop.

So why I am getting error?

Upvotes: 1

Views: 1380

Answers (3)

Andy Turner
Andy Turner

Reputation: 140318

Anonymous classes become separate classes at compile time. The following code is roughly equivalent:

class ContainingClass {
  void myMethod() {
    for(int i = 0; i < 10; ++i) {
      outerTimer = new MyAnonymousTimer();

      outerTimer.run();
      outerTimer.scheduleRepeating(tmptimerDuration);
    }
  }
}

class MyAnonymousTimer extends Timer {
  @Override
  public void run() {        
    if(stopTimer) {
      cancel();
      break; // break cannot be used outside of a loop or a switch
    }

   repeatLoop();
  }         
}

(the name MyAnonymousTimer is not the actual name of the class; it is more like ContainingClass$1)

As such, the break isn't really in the loop; it is mere syntactic convenience that you can declare it inline with the loop.

You need to use return, like you would to stop execution of any other void method.

Upvotes: 3

Luca Marzi
Luca Marzi

Reputation: 806

You see that the "break" is inside the loop graphically but the "break" is inside a different scope indeed. This way the break instruction is executed inside the inner scope (and notice that there's a new one for each iteration).

What does the repeatLoop do? Because I was thinking to a different solution but I have to know its behavior.

Upvotes: 0

Maroun
Maroun

Reputation: 95968

You can have a final boolean variable (that can be accessed from the function), and set its value to true when you should break. Then, in the for loop, you simply check if the variable true and break.

Your code doesn't work because the break is not really inside the for loop, it's inside the anonymous function that's in another scope.

Upvotes: 1

Related Questions