1、switch语句的case穿透
case穿透是如何产生的?
如果switch语句中,case省略了break语句,就会开始case穿透。
case穿透的现象:
当开始case穿透,后续的case就不会在具有匹配效果,内部的语句就会直接执行,知道遇到break,或者switch语句执行完毕,才会结束。
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int week = sc.nextInt();
switch(week) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("工作日");
break;
case 6:
case 7:
System.out.println("休息日");
break;
default:
System.out.println("输入有误");
break;
}
}
2、for语句的组成?
for(初始语句; 条件判断语句; 条件控制语句){
循环语句;
}
//利用for循环求1-100的偶数和
public static void main(String[] args){
int sum = 0; //定义求和变量
for(int i = 1; i <= 100; i++) {
if(i%2==0) {
sum += i;
}
}
System.out.println("1-100的偶数和为:" + sum);
}
3、for循环输出 “水仙花数”
水仙花数:各位数³ + 十位数³ + 百位数³ = 原三位数
public static void main(String[] args) {
for(int i = 100; i <= 999; i++) {
int ge = i % 10;
int shi = i / 10 % 10;
int bai = i / 100 % 10;
if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) {
System.out.println(i);
}
}
}
4、while语句 “珠穆朗玛峰”
基本格式:
初始化语句;
while (条件判断语句) {
循环语句;
条件控制语句;
}
/*
一张厚度为0.1毫米的纸对折多少次等达到珠穆朗玛峰的高度
即 8844430 毫米
*/
public static void main(String[] args) {
int paper = 0.1;
int zmlmf = 8844430;
int count = 0;
while (paper <= zmlmf) {
count ++;
paper += 2;
}
System.out.println("对折次数为:" + count);
}
5、do-while循环语句
初始化语句;
do {
循环体语句;
条件控制语句;
} while(条件判断语句)
区别在于:先循环再判断
6、循环中的跳转和终止语句
跳转:continue跳过某次循环继续执行;
终止:break终止后续的循环;
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if(i == 4) {
System.out.println(i + "楼到了!");
continue;
}
i ++;
}
for (int age = 18; age <= 80; age ++) {
if (age == 60) {
System.out.println(age + "岁该退休了");
break;
}
}
}
7、死循环的跳出案例
public static void main(String[] args) {
//加入标号名lo
lo:while(true) {
System.out.println("请输入星期数,输入0则退出循环");
Scanner sc = new Scanner(System.in);
int week = sc.nextInt();
switch(week) {
case 0:
break lo;
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("工作日");
break;
case 6:
case 7:
System.out.println("休息日");
break;
default:
System.out.println("输入有误");
break;
}
}
}
8、Random产生随机数
import java.util.Random;
public static void main(String[] args) {
Random r = new Random();
int i = 1;
while (i <= 10) {
int num = r.nextInt(10) + 1; //1-10
System.out.println(num);
i ++;
}
}