《条件循环》
目录
一、条件语句
if…else if…else条件语句(多用于逻辑表达式判断)
【成绩结果判断】代码示例:
public class Main {
public static void main(String[] args) {
System.out.println("请输入成绩:");
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
if (score >= 0 && score < 60) {
if (score < 40) {
System.out.println("重修");
} else {
System.out.println("补考");
}
} else if (score >= 60 && score < 80) {
System.out.println("及格");
} else if (score >= 80 && score < 90) {
System.out.println("良好");
} else if (score >= 90 && score <= 100) {
System.out.println("优秀");
} else {
System.out.println("非法成绩格式!");
}
}
}
switch…case…default条件语句(多用于值判断)
【账户等级判断】代码示例:
public class Main {
public static void main(String[] args) {
System.out.println("请输入账户等级:");
Scanner sc = new Scanner(System.in);
int lv = sc.nextInt();
switch (lv) {
case 0:
System.out.println("普通用户");
break;
case 1:
case 2:
System.out.println("青铜会员");
break;
case 3:
case 4:
System.out.println("白银会员");
break;
case 5:
System.out.println("黄金会员");
break;
default:
System.out.println("非法参数!");
break;
}
}
}
二、循环语句
循环三要素:变化因子、变化范围、变化幅度。
for循环
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
while循环
int j = 0;
while (j < 5) {
System.out.println(j);
j++;
}
do…while循环(循环体至少执行一次)
int k = 5;
do {
System.out.println(k);
k--;
} while (k > 0);
嵌套循环(多维数据处理)
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print("⭐");
}
System.out.println();
}
影响循环关键字:break、continue、return
- break打断循环
- continue跳过本次循环执行下一次
- return针对方法,方法停止结束执行。
for (int i = 0; i < 6; i++) {
if (i == 3) {
//break;
//continue;
return;
}
System.out.println(i);
}
System.out.println("程序执行结束!");
总结
重点
- 条件判断;
- 循环语句;
- 影响循环的三个关键字。
难点
- 嵌套循环。
480

被折叠的 条评论
为什么被折叠?



