Java的条件语句
语法
if语句的语法如下:
if(布尔表达式
){
}
例如:
public class Test {
public static void main(String args
[]){
int x
= 50;
if( x
> 20 ){
System
.out
.print("这是 if 语句");
}
}
}
以上编译运行的结果就是这是 if 语句
if…else语句
if…else语句的语法如下:
if(布尔表达式
){
}else{
}
例如:
public class Test {
public static void main(String args
[]){
int x
= 50;
if( x
< 20 ){
System
.out
.print("这是 if 语句");
}else{
System
.out
.print("这是 else 语句");
}
}
}
以上编译运行的结果就是这是 else 语句
if…else if…else语句
if 语句后面可以跟 else if…else 语句
使用 if,else if,else 语句的时候,需要注意下面几点:if 语句至多有 1 个 else 语句,else 语句在所有的 else if 语句之后。if 语句可以有若干个 else if 语句,它们必须在 else 语句之前。一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行。
if…else语句的语法如下:
if(布尔表达式
1){
}else if(布尔表达式
2){
}else if(布尔表达式
3){
}else {
}
例如:
public class Test {
public static void main(String args
[]){
int x
= 30;
if(x
== 10){
System
.out
.print("值为"+x
);
}else if(x
== 20){
System
.out
.print("值为"+x
);
}else if(x
== 30){
System
.out
.print("值为"+x
);
}else{
System
.out
.print("这是 else 语句");
}
}
}
以上编译运行的结果就是值为30
嵌套的if…else语句
嵌套的 if…else 语法格式如下:
if(布尔表达式
1){
if(布尔表达式
2){
}
}
例如:
public class Test {
public static void main(String args
[]){
int x
= 50;
int y
= 20;
if(x
== 50){
if(y
== 20){
System
.out
.print("X = "+x
+" and Y = "+y
);
}
}
}
}
以上编译运行的结果就是X = 50 and Y = 20