我怎样才能跳出 if 块?

Cod*_*tic 4 java controls if-statement

考虑这个代码示例。

这段代码只是为了解释我的问题。

boolean status = false;
for ( int i = 0; i <= 5; i++ ) {
    if ( i == 4 ) { 
        System.out.println ( "Enter into first if" );
        if ( status == false ) {
               System.out.println ( "Enter into second if" );
               status = true;
               if ( status == true ) {
                    System.out.println ( "Enter into third if" );
                    //third if body
               }
               //second if body                             
        }
        //first if body
        System.out.println ( "Before exiting first if" );
    }
}
Run Code Online (Sandbox Code Playgroud)

我想做的就是从第三个 if 到第一个 if。

我们知道break、continue都可以在循环中使用。我们可以对块实现同样的效果吗?

McD*_*ell 7

好吧,你可以打破任何块:

public class Bar {

  static void foo(boolean b) {
    foo: {
      if (b) {
        break foo;
      }
      System.out.println(b);
    }
  }

  public static void main(String[] args) {
    foo(true);
    foo(false);
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

false
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Java 语言规范。

但是,如果您尝试在我的一个项目中交付此代码,我们可能会说。