Java if else if else判断语句
if 语句后面可以跟 elseif…else 语句,这种语句可以检测到多种可能的情况。
语法
if(布尔表达式 1){ //如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){ //如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){ //如果布尔表达式 3的值为true执行代码
}else { //如果以上布尔表达式都不为true执行代码
}
总结
if 语句至多有 1 个 else 语句,else 语句在所有的 elseif 语句之后。
if 语句可以有若干个 elseif 语句,它们必须在 else 语句之前。
一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行。
例子
public class ddd {
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("?? else ??");
}
}
}
代码编译运行结果如下:
Value of X is 30
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。