【问题标题】:How to convert my enumeration code into a switch如何将我的枚举代码转换为开关
【发布时间】:2019-06-27 13:22:54
【问题描述】:

在我的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 语句,但收到错误:

枚举 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;

【问题讨论】:

  • 在编写涉及 switch 的代码时,您是否面临任何特定问题?这看起来像是家庭作业,所以不能在没有先看到任何诚实尝试的情况下简单地用勺子喂你解决方案。
  • 从上面看,你似乎没有尝试过使用switch(还)。您最好的办法是尝试使用它,然后发布一个问题如果您在这样做时遇到了特定问题。 (将上面的转换为switch 非常简单,不会遇到问题。)
  • switch(ct) 知道ct 的类型,所以CustomerType. 部分在case 部分中是不必要的
  • Pshemo 是对的。看到这个答案:stackoverflow.com/a/8109054/7098259

标签: java switch-statement


【解决方案1】:

你想切换到变量 ct

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

如果您需要更多帮助,请阅读these Java Docs

【讨论】:

    【解决方案2】:

    试试这个: (很简单)

    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;
    
       }
    

    【讨论】:

    • 我试过这个,认为它不起作用。我收到错误消息“枚举 switch case 标签必须是枚举常量的非限定名称”
    • @AveryO 为了获得更好的帮助,请在您的问题下使用编辑选项,并在错误消息中包含您的无效代码。
    • 你的枚举是如何声明的?
    猜你喜欢
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2010-09-06
    相关资源
    最近更新 更多