开关盒中需要的常量表达式

时间:2016-04-26 12:34:50

标签: java switch-statement constants

我已经为我的字符串初始化了常量表达式。这里似乎有什么问题?

我得到的错误是"需要持续表达"。

以下是我的代码,

public class VatCalculator {

    private static int ONBOARD_SALE =1;
    private static int ONBOARD_SERVICE =2;
    private static int PREORDER_SALE =3;
    private static int PREORDER_SERVICE =4;

    private static final Map<String, Integer> serviceMap = new HashMap<String, Integer>();
    static {
        serviceMap.put("onboardSale", ONBOARD_SALE);
        serviceMap.put("onboardService", ONBOARD_SERVICE);
        serviceMap.put("preorderSale", PREORDER_SALE);
        serviceMap.put("preorderService", PREORDER_SERVICE);
    }



public static double calculate(String serviceGroup) {

int type = serviceMap.get(serviceGroup);

switch(type) {
//error at below line
case ONBOARD_SALE:
        //do something

default:break;
    }
}

2 个答案:

答案 0 :(得分:1)

使用此:

private static final int ONBOARD_SALE = 1;

答案 1 :(得分:0)

检查大括号

    public class VatCalculator {

        private static int ONBOARD_SALE =1;
        private static int ONBOARD_SERVICE =2;
        private static int PREORDER_SALE =3;
        private static int PREORDER_SERVICE =4;

        private static final Map<String, Integer> serviceMap = new HashMap<String, Integer>();
        static {
            serviceMap.put("onboardSale", ONBOARD_SALE);
            serviceMap.put("onboardService", ONBOARD_SERVICE);
            serviceMap.put("preorderSale", PREORDER_SALE);
            serviceMap.put("preorderService", PREORDER_SERVICE);
        }


    public static double calculate(String serviceGroup) {

        int type = serviceMap.get(serviceGroup);

        switch(type) {
            //error at below line
            case ONBOARD_SALE:
                    //do something

            default:break;
        }
    }
    } //<-- add like this brace