目录

if...else statement

if语句后面可以跟一个可选的else语句,该语句在布尔表达式为false时执行。

语法 (Syntax)

以下是if ... else语句的语法 -

if(Boolean_expression) {
   // Executes when the Boolean expression is true
}else {
   // Executes when the Boolean expression is false
}

如果布尔表达式的计算结果为true,那么将执行if代码块,否则将执行代码块。

流程图 (Flow Diagram)

如果是其他声明

例子 (Example)

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

这将产生以下结果 -

输出 (Output)

This is else statement

if...else if...else (The if...else if...else Statement)

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

当使用if,else if,else语句时,请记住几点。

  • 一个if可以有零个或一个其他的,它必须在任何其他if之后。

  • 如果是的话,if可以有零到多个,并且它们必须在else之前。

  • 一旦else成功,其余的其他if或者其他都将被测试。

语法 (Syntax)

以下是if ... else语句的语法 -

if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
   // Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
   // Executes when the Boolean expression 3 is true
}else {
   // Executes when the none of the above condition is true.
}

例子 (Example)

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");
      }
   }
}

这将产生以下结果 -

输出 (Output)

Value of X is 30
↑回到顶部↑
WIKI教程 @2018