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 教师闺蜜祝福语简短