Java中的“ if ... else if ... else”语句是什么以及如何使用?

if语句后可以是一个可选的else if ... else语句,这对于使用单个if ... else if语句测试各种条件非常有用。

使用if,else if,else语句时,有几点需要牢记。

  • 一个if可以有零个或另一个,并且必须在其他if个之后。

  • 一个if可以具有零个或多个其他if,并且它们必须排在else之前。

  • 如果else if成功,则不会测试其余else if。

语法

if(Boolean_expression 1) {
   //当布尔表达式1为true时执行
}else if(Boolean_expression 2) {
   //当布尔表达式2为true时执行
}else if(Boolean_expression 3) {
   //当布尔表达式3为true时执行
}else {
   //当以上条件都不为真时执行。
}

示例

public class Test {
   public static void main(String args[]) {
      int x = 30;
      if( x == 10 ) {
         System.out.print("Value of X is 10");
      }else if( x == 20 ) {
         System.out.print("Value of X is 20");
      }else if( x == 30 ) {
         System.out.print("Value of X is 30");
      }else {
         System.out.print("This is else statement");
      }
   }
}

输出结果

Value of X is 30