如何把我的枚举代码转换成一个开关

问题描述 投票:-2回答:2

在我CustomerTypeApp类,我需要改变,而不是使用的if语句链开关的getDiscountPercent方法。下面是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语句,但会收到错误:

枚举开关case标签必须是枚举常量的非限定名称

  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;
java switch-statement
2个回答
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;

   }

0
投票

要切换的变数CT

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

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

© www.soinside.com 2019 - 2024. All rights reserved.