1.语法格式1
if(布尔表达式){
// 语句
}
如果布尔表达式结果为true,执行if中的语句,否则不执行。
比如:小明,如果这次考试考到90分或以上,给你奖励一个鸡腿。
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}
语法格式2
if(布尔表达式){
// 语句1
}else{
// 语句2
}
如果布尔表达式结果为true,则执行if中语句,否则执行else中语句。
比如:小明,如果这次考到90分以上,给你奖励一个大鸡腿,否则奖你一个大嘴巴子。
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}else{
System.out.println("挨大嘴巴子!!!");
}
语法格式3
if(布尔表达式1){
// 语句1
}else if(布尔表达式2){
// 语句2
}else{
// 语句3
}
表达式1成立,执行语句1,否则表达式2成立,执行语句2,否则执行语句3
比如:考虑到学生自尊,不公开分数排名,因此:
分数在 [90, 100] 之间的,为优秀
分数在 [80, 90) 之前的,为良好
分数在 [70, 80) 之间的,为中等
分数在 [60, 70) 之间的,为及格
分数在 [ 0, 60) 之间的,为不及格
错误数据
按照上述办法通知学生成绩
f(score >= 90){
System.out.println("优秀");
}else if(score >= 80 && score < 90){
System.out.println("良好");
}else if(score >= 70 && score < 80){
System.out.println("中等");
}else if(score >= 60 && score < 70){
System.out.println("及格");
}else if(score >= 0 && score < 60){
System.out.println("不及格");
}else{
System.out.println("错误数据");
}
代码风格推荐
int x = 10;
if (x == 10) {
// 语句1
} else {
// 语句2
}
分号问题
int x = 20;
if (x == 10);
{
System.out.println("hehe");
}
// 运行结果
hehe
此处多写了一个 分号, 导致分号成为了 if 语句的语句体, 而 { } 中的代码已经成为了和一个 if 无关的代码块.
悬垂 else 问题
int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");
if / else 语句中可以不加 大括号 . 但是也可以写语句(只能写一条语句). 此时 else 是和最接近的 if 匹配.
但是实际开发中我们 不建议 这么写. 最好加上大括号.
【代码练习】
1. 判断一个数字是奇数还是偶数
int num = 10;
if (num % 2 == 0) {
System.out.println("num 是偶数");
} else {
System.out.println("num 是奇数");
}
2. 判断一个数字是正数,负数,还是零
int num = 10;
if (num > 0) {
System.out.println("正数");
} else if (num < 0) {
System.out.println("负数");
} else {
System.out.println("0");
}
3. 判断一个年份是否为闰年
int year = 2000;
if (year % 100 == 0) {
// 判定世纪闰年
if (year % 400 == 0) {
System.out.println("是闰年");
} else {
System.out.println("不是闰年");
}
} else {
// 普通闰年
if (year % 4 == 0) {
System.out.println("是闰年");
} else {
System.out.println("不是闰年");
}
}