如何将我的枚举代码转换为交换机

时间:2019-02-03 17:07:58

标签: java switch-statement

在我的CustomerTypeApp类中,我需要更改getDiscountPercent方法以使用开关而不是if语句链。这是if语句版本:

public static double getDiscountPercent(CustomerType ct) {
        double discountPercent = 0;
        if (ct == CustomerType.RETAIL) {
            discountPercent = 0.156;
        } else if (ct == CustomerType.TRADE) {
            discountPercent = 0.30;
        } else if (ct == CustomerType.COLLEGE) {
            discountPercent = 0.20;
        }
        return discountPercent;
    }
}

下面是我尝试过的switch语句,但是收到错误:

  

枚举开关大小写标签必须是枚举常量的不合格名称

  double discountPercent = 0;

  switch(ct) {
      case CustomerType.RETAIL :
        discountPercent = 0.156;
        break;
     case CustomerType.TRADE :
        discountPercent = 0.30;
        break;
     case CustomerType.COLLEGE :
        discountPercent = 0.20;
        break;
     default :
        discountPercent = 0;
  }
  return discountPercent;

2 个答案:

答案 0 :(得分:0)

您要切换为ct

switch(ct) {
        case CustomeType.retail:
            /*Command*/
            break;
        case CustomerType.TRADE:
            /*Command*/
            break;
        default:
            /*else*/
}

如果您需要进一步的帮助,请阅读these Java Docs

答案 1 :(得分:0)

尝试一下: (非常简单)

public static double getDiscountPercent(CustomerType ct) {

      double discountPercent = 0;

      switch(ct) {
         case CustomerType.RETAIL :
            discountPercent = 0.156;
            break;
         case CustomerType.TRADE :
            discountPercent = 0.30;
            break;
         case CustomerType.COLLEGE :
            discountPercent = 0.20;
            break;
         default :
            discountPercent = 0;
      }
      return discountPercent;

   }