-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsection.java.controlflow.xml
More file actions
113 lines (98 loc) · 2.5 KB
/
section.java.controlflow.xml
File metadata and controls
113 lines (98 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?xml version="1.0" encoding="UTF-8"?>
<chapter id="ControlFlow">
<title>流程控制</title>
<section>
<title>Switch</title>
<section>
<title>yield</title>
<programlisting>
<![CDATA[
package cn.netkiller.demo;
public class DemoSwitch {
public DemoSwitch() {
}
public static void main(String[] args) {
var number = 4;
var operation = "平方";
var result = switch (operation) {
case "立方" -> {
yield number * number * number;
}
case "平方" -> {
yield number * number;
}
default -> number;
};
System.out.println(result);
}
}
]]>
</programlisting>
<para>不必为break每个 case 块定义一个语句,我们可以简单地使用箭头语法</para>
<programlisting>
<![CDATA[
int money = 3;
String cn = switch (money) {
case 1 -> "壹";
case 2 -> "贰";
case 3 -> "叁";
case 4 -> "肆";
case 5 -> "伍";
case 6 -> "陆";
case 7 -> "柒";
case 8 -> "捌";
case 9 -> "玖";
case 10 -> "拾";
default -> "零";
};
System.out.println(cn);
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller.test;
public class Test {
public static void main(String[] args) {
withSwitchExpression(Fruit.APPLE);
withReturnValue(Fruit.AVOCADO);
withYield(Fruit.VEGETABLES);
}
private static void withSwitchExpression(Fruit fruit) {
switch (fruit) {
case APPLE, PEAR -> System.out.println("普通水果");
case MANGO, AVOCADO -> System.out.println("进口水果");
default -> System.out.println("未知水果");
}
}
private static void withReturnValue(Fruit fruit) {
System.out.println(switch (fruit) {
case APPLE, PEAR -> "普通水果";
case MANGO, AVOCADO -> "进口水果";
default -> "未知水果";
});
}
private static void withYield(Fruit fruit) {
String text = switch (fruit) {
case APPLE, PEAR, MANGO, AVOCADO -> {
System.out.println("水果: " + fruit);
yield "水果: " + fruit;
}
case VEGETABLES -> {
System.out.println("蔬菜: " + fruit);
yield "蔬菜:" + fruit;
}
default -> {
yield "未知食物";
}
};
System.out.println(text);
}
public enum Fruit {
APPLE, PEAR, MANGO, AVOCADO, VEGETABLES
}
}
]]>
</programlisting>
</section>
</section>
</chapter>