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 生日开业蛋糕祝福语简短