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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西