Java if-else-if 阶梯语句
java programming java8java technologies object oriented programming
if 语句后可以跟一个可选的 else if...else 语句,这对于使用单个 if...else if 语句测试各种条件非常有用。
使用 if、else if、else 语句时,需要注意以下几点。
if 可以包含零个或一个 else,并且 else 必须位于任何 else if 之后。
if 可以包含零到多个 else if,并且 else 必须位于 else 之前。
一旦 else if 成功,则不会再测试剩余的 else if 或 else。
语法
以下是if...else 语句 −
if(Boolean_expression 1) { // 当布尔表达式 1 为真时执行 }else if(Boolean_expression 2) { // 当布尔表达式 2 为真时执行 }else if(Boolean_expression 3) { // 当布尔表达式 3 为真时执行 }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