Day06-switch结构
switch多选择结构
package com.gong.struct;
//case穿透
public class SwitchDemo01 {
public static void main(String[] args) {
char grade = 'A';
switch (grade){
case 'A':
System.out.println("优秀");
break;//可选
case 'B':
System.out.println("良好");
break;//可选
case 'C':
System.out.println("及格");
break;//可选
case 'D':
System.out.println("再接再厉");
break;//可选
case 'E':
System.out.println("挂科了");
break;//可选
default:
System.out.println("输入有误");
break;
}
}
}
输出
优秀
String类型的
public class SwitchDemo02 {
public static void main(String[] args) {
String name = "小赵";
//JDK7新特性,表达式结果可以是字符串。
switch (name){
case "小赵":
System.out.println("你好!");
break;
case "玄月":
System.out.println("走开!");
break;
default:
System.out.println("输入有误");
break;
}
}
}
输出
你好!
总结

循环结构
while循环结构
输出1-5
public class WhileDemo01 {
public static void main(String[] args) {
//输出1-5
int i = 0;
while (i<5){
i++;
System.out.println(i);
}
}
}
输出
1
2
3
4
5
死循环
public class WhileDemo01 {
public static void main(String[] args) {
//死循环
while (true){
//等待客户端连接
//定时检查
//......
}
}
}
算和
public class WhileDemo02 {
public static void main(String[] args) {
//计算1+...+100的结果
int i=0;
int sum=0;
while (i<=100){
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
输出
5050
总结

作业
假设有一张纸可对折无限次,它的厚度为0.1毫米,珠穆朗玛峰的高度为8848.86米,求这张纸对折多少次后它的厚度会超过珠峰的高度。
package com.stx.p2.gonghaoyue;
//假设有一张纸可对折无限次,它的厚度为0.1毫米,珠穆朗玛峰的高度为8848.86米,求这张纸对折多少次后它的厚度会超过珠峰的高度。
public class Demo01 {
public static void main(String[] args) {
double x = 0.1;
int y = 0;
while (x<=8848860){
x=x*2;
y++;
System.out.println("对折第"+y+"次的高度为"+x+"mm");
}
System.out.println("所以对折"+y+"次后,这张纸的厚度会超过珠峰的高度。");
}
}
输出
对折第1次的高度为0.2mm
对折第2次的高度为0.4mm
对折第3次的高度为0.8mm
对折第4次的高度为1.6mm
对折第5次的高度为3.2mm
对折第6次的高度为6.4mm
对折第7次的高度为12.8mm
对折第8次的高度为25.6mm
对折第9次的高度为51.2mm
对折第10次的高度为102.4mm
对折第11次的高度为204.8mm
对折第12次的高度为409.6mm
对折第13次的高度为819.2mm
对折第14次的高度为1638.4mm
对折第15次的高度为3276.8mm
对折第16次的高度为6553.6mm
对折第17次的高度为13107.2mm
对折第18次的高度为26214.4mm
对折第19次的高度为52428.8mm
对折第20次的高度为104857.6mm
对折第21次的高度为209715.2mm
对折第22次的高度为419430.4mm
对折第23次的高度为838860.8mm
对折第24次的高度为1677721.6mm
对折第25次的高度为3355443.2mm
对折第26次的高度为6710886.4mm
对折第27次的高度为1.34217728E7mm
所以对折27次后,这张纸的厚度会超过珠峰的高度。
本文介绍了Java中的switch多选择结构,展示了其在字母等级判断中的应用,并提及了JDK7开始支持字符串作为switch表达式的特性。同时,通过实例讲解了while循环的基本用法,包括常规循环和死循环,并演示了计算连续加法的例子。最后,提出了一个实际问题:一张0.1毫米厚的纸对折多少次后会超过珠穆朗玛峰的高度,通过while循环计算得出答案。
953

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



