Java基础学习笔记 - Day03 - 第二章 判断语句
Java基础学习笔记 - Day03 - 第二章 判断语句
系统:Win10
JDK:1.8.0_121
2.1 判断语句1 —— if
- if语句第一种格式:if
if(判断条件) {
语句体;
}
- 执行流程
- 首先条件判断看其结果是true还是false
- 如果是true就执行语句体
- 如果是false就不执行语句体
public static void main(String[] args){
int age = 16;
System.out.println("回家路上看到一家网吧!");
if(age >= 18) {
System.out.println("上一会网!");
}
System.out.println("回家!");
}
2.2 判断语句2 —— if … else
- if语句第二种格式:if … else
if(判断条件) {
语句体1;
}else {
语句体2;
}
- 执行流程
- 首先条件判断看其结果是true还是false
- 如果是true就执行语句体1
- 如果是false就执行语句体2
public static void main(String[] args){
// 判断给定的数是奇数还是偶数
int num = 6;
if(num % 2 == 0) {
System.out.println("偶数!");
} else {
System.out.println("奇数!");
}
}
2.3 判断语句3 —— if … else if … else
- if语句第三种格式:if … else if … else
if(判断条件1) {
语句体1;
}else if(判断条件2) {
语句体2;
}
...
}else if(判断条件n) {
语句体n;
} else {
语句体n+1;
}
- 执行流程
- 首先判断条件1看其结果是true还是false
- 如果是true就执行语句体1
- 如果是false就继续判断条件2看其结果是true还是false
- 如果是true就执行语句体2
- 如果是false就继续判断条件3看其结果是true还是false
- …
- 如果没有任何关系表达式为true,就执行语句体n+1
public static void main(String[] args){
// x和y的关系满足如下:
// x>=3 y = 2x + 1;
//‐1<=x<3 y = 2x;
// x<=‐1 y = 2x – 1;
// 根据给定的x的值,计算出y的值并输出。
int x = 5;
int y;
if (x >= 3) {
y = 2 * x + 1;
} else if (-1 <= x && x <3) {
y = 2 * x;
} else {
y = 2 * x - 1;
}
System.out.println("y的值是:" + y);
}
2.4 语句练习
- 指定考试成绩,判断学生成绩
- 90-100 优秀
- 80-89 好
- 70-79 良
- 60-69 及格
- 60以下 不及格
public static void main(String[] args){
int score = 96;
if (score >= 90 && score <= 100) {
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("分数错误!");
}
}
2.5 if语句和三元运算符的互换
在某些简单的应用中,if语句是可以和三元运算符互换使用的
- 取两个数字当中的最大值
public static void main(String[] args){
int a = 10;
int b = 20;
// 定义最大值
int max1,max2;
// if-else实现
if (a > b) {
max1 = a;
} else {
max1 = b;
}
System.out.println(max1);
// 三元运算符实现
max2 = a > b ? a : b;
System.out.println(max2);
}