gpt4 book ai didi

java - 使用枚举切换大小写会导致重复

转载 作者:行者123 更新时间:2023-12-01 07:10:26 25 4
gpt4 key购买 nike

当我使用 for-each 循环和 switch 语句迭代一个简单的枚举测试器来输出枚举值时,我看到了对我来说似乎很奇怪的行为。

代码:

public class EnumTest {

private Number number;

public EnumTest(Number number) {
this.number = number;
}
public enum Number {
ONE,
TWO,
THREE,
FOUR,
FIVE;
}
private void tellItLikeItIs() {
switch (number) {
case ONE:
System.out.println("ONE");
case TWO:
System.out.println("TWO");
case THREE:
System.out.println("THREE");
case FOUR:
System.out.println("FOUR");
case FIVE:
System.out.println("FIVE");
}
}
public static void main(String[] args) {
for (Number n : Number.values()) {
EnumTest et = new EnumTest(n);
et.tellItLikeItIs();
System.out.println();
}
}
}

输出:

    ONE
TWO
THREE
FOUR
FIVE

TWO
THREE
FOUR
FIVE

THREE
FOUR
FIVE

FOUR
FIVE

FIVE

为什么每次调用都会返回自身以及所有后续值?

最佳答案

那是因为你忘记了 break; 语句...

private void tellItLikeItIs() { 
switch (number) {
case ONE:
System.out.println("ONE");
break;
case TWO:
System.out.println("TWO");
break;
case THREE:
System.out.println("THREE");
break;
case FOUR:
System.out.println("FOUR");
break;
case FIVE:
System.out.println("FIVE");
break;
}
}

了解有关 switch 语句的更多信息 here :

Without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered

关于java - 使用枚举切换大小写会导致重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15501287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com