Java中的“ if ... else if ... else”语句是什么以及如何使用?
if语句后可以是一个可选的elseif...else语句,这对于使用单个if...elseif语句测试各种条件非常有用。
使用if,elseif,else语句时,有几点需要牢记。
一个if可以有零个或另一个,并且必须在其他if个之后。
一个if可以具有零个或多个其他if,并且它们必须排在else之前。
如果elseif成功,则不会测试其余elseif。
语法
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
热门推荐
10 情侣祝福语古文简短独特
11 酒店伴娘祝福语简短
12 晚上甜蜜的祝福语简短
13 给新娘简短的祝福语
14 当爸爸的简短祝福语
15 洛宁新年祝福语大全简短
16 新年祝福语简短搞笑幽默
17 结婚祝福语大全简短霸气
18 新人结婚祝福语简短高端