文章目录
前言
本文详细介绍了 Java 中的控制流语句,包括条件语句(if/switch)和循环语句(for/while/do-while),并通过实际案例演示其使用方法。
一、switch 的扩展知识点
1. if 第三种格式
一般用于对范围的判断:
public class Main {
public static void main(String[] args) {
int score = 80;
// if 对范围判断
if (score >= 90 && score <= 100) {
System.out.println("A"); // 连续型if,离散型switch
}
}
}
2. switch 语句
适用于有限个离散值的判断:
// switch 基本语法
switch(表达式) {
case 值1:
// 代码
break;
case 值2:
// 代码
break;
default:
// 代码
}
注意事项:
switch
支持的类型:byte
,short
,int
, 枚举类型(JDK5+),String
(JDK7+)default
位置影响:- 在顶部:必须加
break
- 在尾部:可省略
break
- 在顶部:必须加
3. 练习:休息日与工作日
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int day = scanner.nextInt();
switch(day) {
case 1, 2, 3, 4, 5: // JDK12+ 多值匹配语法
System.out.println("Weekday");
break;
case 6, 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
}
}
二、循环语句
1. for 循环
for (初始化语句; 条件判断语句; 条件控制语句) {
// 循环体语句
}
2. while 循环
初始化语句;
while (条件判断语句) {
// 循环体语句
// 条件控制语句
}
练习:打印 1~100:
public class Main {
public static void main(String[] args) {
int n = 1;
while (n <= 100) {
System.out.println(n);
n++;
}
}
}
3. for 与 while 的对比
特性 | for 循环 | while 循环 |
---|---|---|
变量作用域 | 循环内 | 循环外可访问 |
适用场景 | 已知循环次数/范围 | 未知循环次数,只知结束条件 |
案例:回文数
public class Main {
public static void main(String[] args) {
int x = 121;
int temp = x; // 保存原数字
int num = 0;
while (x != 0) {
int ge = x % 10; // 获取个位数
x = x / 10; // 去掉个位数
num = ge + num * 10; // 构建反转数
}
System.out.println(temp == num ? "Palindrome" : "Not Palindrome");
}
}
案例:求商和余数
public class Main {
public static void main(String[] args) {
int dividend = 100; // 被除数
int divisor = 10; // 除数
int quotient = 0; // 商
int remainder = dividend; // 余数(初始为被除数)
while (remainder >= divisor) {
remainder -= divisor;
quotient++;
}
System.out.println("商: " + quotient);
System.out.println("余数: " + remainder);
}
}
do…while 循环
先执行后判断:
初始化语句;
do {
// 循环体语句
// 条件控制语句
} while (条件判断语句);
二、无限循环与跳转控制语句
无限循环写法:
// 方式1
for (;;) {
// 循环体
}
// 方式2
while (true) {
// 循环体
}
跳转控制语句:
continue
:结束本次循环,进入下一次循环break
:结束整个循环
案例:逢7过(遇到7的倍数或含7的数跳过):
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
// 跳过7的倍数或含7的数
if (i % 7 == 0 || i % 10 == 7 || i / 10 == 7) {
continue;
}
System.out.println(i);
}
}
}
总结
-
条件语句选择:
- 范围判断 →
if
- 离散值匹配 →
switch
- 范围判断 →
-
循环语句选择:
- 已知次数/范围 →
for
- 未知次数,只知结束条件 →
while
- 至少执行一次 →
do...while
- 已知次数/范围 →
-
跳转控制:
- 跳过单次循环 →
continue
- 终止整个循环 →
break
- 跳过单次循环 →
-
最佳实践:
- 避免无限循环(除非必要)
- 使用明确的循环终止条件
- 合理选择循环结构提高代码可读性
通过掌握这些控制流语句,可以编写出更灵活、高效的 Java 程序。