if-else 条件判断
程序根据条件走不同的路,就像你到了岔路口看路标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Test public void testIfElse() { int score = 85;
if (score >= 60) { System.out.println("及格了"); }
if (score >= 90) { System.out.println("优秀"); } else { System.out.println("还需努力"); }
if (score >= 90) { System.out.println("A - 优秀"); } else if (score >= 80) { System.out.println("B - 良好"); } else if (score >= 60) { System.out.println("C - 及格"); } else { System.out.println("D - 不及格"); } }
|
注意事项
if 后面的条件必须是 boolean 类型(参考 变量与数据类型 布尔章节)
Java不像C语言,不能用 if (1) 代替 if (true)
多分支从上往下匹配,匹配到第一个就停,不会继续往下走
只有一行时可以省略大括号,但不推荐
1 2 3 4 5 6 7 8
| if (score >= 60) System.out.println("及格");
if (score >= 60) { System.out.println("及格"); }
|
简单的二选一可以用三元运算符替代(参考 运算符 三元运算符章节)
switch 分支选择
当你要拿一个值跟很多固定选项比较时,switch 比一堆 if-else 更清晰
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Test public void testSwitch() { int day = 3;
switch (day) { case 1: System.out.println("周一"); break; case 2: System.out.println("周二"); break; case 3: System.out.println("周三"); break; case 6: case 7: System.out.println("周末!"); break; default: System.out.println("周" + day); break; } }
|
⚠️ break 不能忘!
如果忘了 break,会发生穿透(fall-through):匹配到之后的所有case都会执行
1 2 3 4 5 6 7 8 9 10 11
| switch (day) { case 1: System.out.println("周一"); case 2: System.out.println("周二"); case 3: System.out.println("周三"); }
|
switch支持的类型
byte、short、int、char — 基本整型
String — Java 7 开始支持
enum — 枚举类型
❌ 不支持 long、float、double、boolean
Java 14+ 新语法:switch表达式(了解)
1 2 3 4 5 6 7 8 9
| String result = switch (day) { case 1 -> "周一"; case 2 -> "周二"; case 3 -> "周三"; case 6, 7 -> "周末"; default -> "周" + day; }; System.out.println(result);
|
for 循环
知道要循环多少次时用 for,最最最常用的循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void testFor() {
for (int i = 1; i <= 5; i++) { System.out.println("i = " + i); }
}
|
常见用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| for (int i = 10; i >= 1; i--) { System.out.println(i); }
for (int i = 1; i <= 10; i += 2) { System.out.println(i); }
int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } System.out.println("1到100的和 = " + sum);
|
嵌套循环
1 2 3 4 5 6 7
| for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.printf("%d×%d=%-4d", j, i, i * j); } System.out.println(); }
|
增强for循环(for-each)
遍历数组或集合时更简洁,不需要下标
1 2 3 4 5 6 7 8 9 10 11
| String[] fruits = {"苹果", "香蕉", "橙子"};
for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); }
for (String fruit : fruits) { System.out.println(fruit); }
|
缺点:拿不到下标 i,如果需要下标就用传统for
while 循环
不知道要循环多少次,只知道”什么时候停”时用 while
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Test public void testWhile() {
int count = 0; while (count < 5) { System.out.println("第" + count + "次"); count++; }
int num = 12345; System.out.print("逆序各位数:"); while (num > 0) { System.out.print(num % 10 + " "); num /= 10; }
}
|
⚠️ 死循环
如果条件永远为true,循环永远不会停 → 程序卡死
1 2 3 4 5 6
| int count = 0; while (count < 5) { System.out.println(count);
}
|
故意的死循环(有时候需要)
do-while 循环
和 while 的区别:先执行一次,再判断条件
保证循环体至少执行一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test public void testDoWhile() {
int x = 10; while (x < 5) { System.out.println("while: " + x); }
x = 10; do { System.out.println("do-while: " + x); } while (x < 5); }
|
典型场景:输入验证
1 2 3 4 5 6 7 8
| Scanner scanner = new Scanner(System.in); int input; do { System.out.print("请输入1-100的数字:"); input = scanner.nextInt(); } while (input < 1 || input > 100);
|
实际开发用得少,大多数场景 for 和 while 就够了
break 和 continue
break:立刻跳出整个循环
1 2 3 4 5 6 7 8 9 10 11
| @Test public void testBreak() {
for (int i = 1; i <= 100; i++) { if (i % 7 == 0) { System.out.println("找到了:" + i); break; } } System.out.println("循环结束"); }
|
continue:跳过本次,继续下一轮循环
1 2 3 4 5 6 7 8 9 10
| @Test public void testContinue() {
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } System.out.println(i); } }
|
break vs continue 对比
| 关键字 |
效果 |
比喻 |
break |
直接离开循环 |
考试交卷走人 |
continue |
跳过当前这一轮,继续下一轮 |
这道题不会,跳过做下一题 |
带标签的break(了解即可)
嵌套循环时,break默认只跳出最内层。想跳出外层循环需要加标签
1 2 3 4 5 6 7 8 9 10
| outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { System.out.println("找到了:i=" + i + " j=" + j); break outer; } } }
|
for vs while vs do-while 怎么选?
| 场景 |
选择 |
例子 |
| 知道循环次数 |
for |
遍历数组、1到100求和 |
| 不知道次数,只知道停止条件 |
while |
读文件到末尾、等待用户输入 |
| 至少执行一次 |
do-while |
输入验证、菜单选择 |
| 遍历集合/数组 |
for-each |
遍历List、遍历String[] |
实际开发中:for 用得最多(80%),while 其次(15%),do-while 很少用(5%)
综合练习
题1:打印1到100中所有的素数
素数:只能被1和自己整除的数(参考 计算机数学基础 密码学数学章节)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void testPrime() { for (int n = 2; n <= 100; n++) { boolean isPrime = true; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { isPrime = false; break; } } if (isPrime) { System.out.print(n + " "); } }
}
|
题2:猜数字游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Test public void testGuessNumber() { int answer = (int)(Math.random() * 100) + 1; Scanner scanner = new Scanner(System.in); int guess; int attempts = 0;
do { System.out.print("猜一个1~100的数字:"); guess = scanner.nextInt(); attempts++;
if (guess > answer) { System.out.println("大了"); } else if (guess < answer) { System.out.println("小了"); } } while (guess != answer);
System.out.println("恭喜猜对了!答案是" + answer + ",你猜了" + attempts + "次");
}
|
题3:FizzBuzz(经典面试题)
打印1到100,能被3整除打印Fizz,能被5整除打印Buzz,都能整除打印FizzBuzz
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test public void testFizzBuzz() { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { System.out.println("FizzBuzz"); } else if (i % 3 == 0) { System.out.println("Fizz"); } else if (i % 5 == 0) { System.out.println("Buzz"); } else { System.out.println(i); } } }
|