Java if-else-if阶梯语句
if语句后可以有一个可选的elseif...elsestatement,这对于使用单个if...elseif语句测试各种条件非常有用。
使用if,elseif,else语句时,有几点需要牢记。
一个if可以有零个或另一个,并且必须在其他if个之后。
一个if可以具有零个或多个其他if,并且它们必须排在else之前。
如果elseif成功,则不会测试其余elseif。
语法
以下是if...else语句的语法-
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 生日广州男生祝福语简短