使用枚举切换案例会导致重复

时间:2013-03-19 13:47:33

标签: java switch-statement

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

代码:

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

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

2 个答案:

答案 0 :(得分:7)

那是因为你忘了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

  

如果没有它们,switch块中的语句将失败:匹配的case标签之后的所有语句将按顺序执行,而不管后续case标签的表达式,直到遇到break语句

答案 1 :(得分:1)

为什么不使用Enum.name()或Enum.toString()方法,如下所示:

    private void tellItLikeItIs() {
     System.out.println(number.name());
    }

    private void tellItLikeItIs() {
    System.out.println(number);
    }