Java 条件语句 if

Java的条件判断
一个 if 语句包含一个布尔表达式和一条或多条语句。

1. 一个if

int score = 88;
if(score > 60){
	System.out.println("及格");
}

输出

及格

2. if else

int score = 50;
 
if(score > 60){
	System.out.println("及格");
}else{
	System.out.println("不及格");
}

输出

不及格

3. if…else if…else 条件判断

if(布尔表达式 1){
   //如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){
   //如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
   //如果布尔表达式 3的值为true执行代码
}else {
   //如果以上布尔表达式都不为true执行代码
}
int score = 88;
 
if(score > 90){
	System.out.println("优秀");
}else if(score > 80){
	System.out.println("良好");
}else if(score > 60){
	System.out.println("及格");
}else{
	System.out.println("不及格");
}

输出

要点:一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行。

良好

4. 多层嵌套 if

判断一个学生是否为四年级,且分数超过60

int score = 88;
int grade = 4;
if(grade == 4 ){
	if(score > 60){
		System.out.println("大学四年级超过60,准予毕业");
	}
}
大学四年级超过60,准予毕业

https://java-er.com/blog/java-if-condition/

猜你喜欢

转载自www.cnblogs.com/yuexiaosheng/p/12340247.html