枚举类型与switch的那点小事

这两天看一个视频,写俄罗斯方块游戏的。发现他写的控制方块方向的是用静态常量来表示。即

public static final int Left = 0;

想想看了effective java,item 30 说过,要用enum代替int常量。我也就想当然地试了一下。

由于之前没写过枚举,有的只是看过。果然出问题了

错误示范,eclipse提示如下错误:The qualified case label Snake.Action.LEFT must be replaced with the unqualified enum constant LEFT

public enum Action{
    LEFT,RIGHT,UP,ROTATE;
}

public Class Test{

    public void test(Action action){
        switch(action){
            case Action.LEFT://这里出错了
                //do sth
                break;
        }
    }

}

正确示范

public void test(Action action){
    switch(action){
        case LEFT://把前面的Action去掉即可
            //do sth
            break;
    }
}
原文地址:https://www.cnblogs.com/baron89/p/2943896.html