Is it bad style to use 'return' to break a for loop in Java?

后端 未结 11 1607
栀梦
栀梦 2020-12-18 21:01

I\'m doing a project with basic Java for a CS class. The project has a for loop nested inside a while loop.

I am not allowed to use break as a wa

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 21:55

    This is about perfect code.

    for(int i; i < stop; i++) {
     boolean flag = true;
    
     while(flag && condition) {
      //some action 
      if(shouldIstop) {
         flag = false;
      }
     }
    }
    

    When you set the flag to false then you will exit from the while, when you will set i to stop then you also will exit from for.

提交回复
热议问题