3-1-1舍入误差问题
在循环中,检测俩个浮点数是否相等需要格外小心。详情请看2-1-3。
for(double x = 0;x != 10;x += 0.1);
上段代码永远无法结束。
3-1-2java14引入的switch语句
1.新版本的swicth
import java.util.Scanner;
public class Study {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
switch (choice){
case 1 -> System.out.println(1);
case 2 -> System.out.println(2);
case 3 -> System.out.println(3);
default -> System.out.println("Bad Input");
}
}
}
case的标签可以是
- 类型为char、byte、short或int类的常量表达式。
- 枚举常量
- 字符串常量
- 多个字符串,用字符串间隔
public class Study {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int seasonNode = 0; //数值
switch (seasonNode){
case 0 -> System.out.println("Spring");
case 1 -> System.out.println("Summer");
case 2 -> System.out.println("Fall");
case 3 -> System.out.println("Winter");
default -> System.out.println("???");
}
String school = "沈阳师范大学"; //字符串
switch(school){
case "沈阳师范大学" -> System.out.println("0001");
case "沈阳工业大学" -> System.out.println("0010");
case "沈阳大学" -> System.out.println("0011");
case "沈阳航空航天大学" -> System.out.println("0100");
default -> System.out.println("can't find anwser");
}
String a = "笔";
switch (a){
case "笔","墨","纸","砚" -> System.out.println("文房四宝");
default -> System.out.println("其他");
}
}
}
输出:
Spring
0001
文房四宝
2.yiled
在switch中,新增了一个yield关键字,他和break很像,都能终止循环,不过yield还会生成一个值,就是swtich表达式的值。
public class Study {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = switch (1){
case 1 -> {
System.out.println("Spring");
yield 6;
}
default -> -1;
};
System.out.println(a);
}
}
上段代码的输出为:
Spring
6
3-1-3中断流程的语句
java提供了一种带标签的break,允许跳出多重循环。我们可以在最外层循环上添加一个以:结尾的表示符作为循环的标签,当循环内有语句break + 标签;时,结束循环。
public class Study {
public static void main(String[] args) {
int a = 0;
int b = 0;
int i = 0,j = 0;
read_data:
for( i = 0;i < 10;i++){
for( j = 0;j < 10;j++){
if(j == 2){
break read_data;
}
}
}
System.out.println(i + " " + j);
}
}
上段代码输出为:
0 2
当j == 2时,在read_data底的整个for循环结束,i 执行了一次,j执行了2次。
3-1-4for each循环
java有一个功能很强的循环结构,可以用来依次处理数组(或者任何其他元素的集合)中的每个元素,而不必考虑指定索引值。
形式 : for(varible : collection) statement
类型 数组(其他) 循环体
public class Study {
public static void main(String[] args) {
int []a = new int[]{1,2,3,4,5};
for(int elements : a){
System.out.println(elements);
}
}
}
输出结果为:
1
2
3
4
5