加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 我想在枚举中创建一个方法?

发布时间:2020-12-15 04:08:43 所属栏目:Java 来源:网络整理
导读:我想在我的CustomerType枚举中添加一个toString方法.我的类返回System.out.println()折扣百分比消息,如果取决于我的cutomerType现在.20因为它是customerType college.我是枚举的新手,我希望能够在我的枚举中添加一个toString方法,根据客户类型打
我想在我的CustomerType枚举中添加一个toString方法.我的类返回System.out.println()折扣百分比消息,如果取决于我的cutomerType现在.20因为它是customerType college.我是枚举的新手,我希望能够在我的枚举中添加一个toString方法,根据客户类型打印“College customer”.我在完成这个方面遇到了一些麻烦?我究竟做错了什么?

听到我的班级:

import java.text.NumberFormat;
public class CustomerTypeApp
{
public static void main(String[] args)
{
    // display a welcome message
    System.out.println("Welcome to the Customer Type Test applicationn");

    // get and display the discount percent for a customer type
    double Customer = getDiscountPercent(CustomerType.College);
    NumberFormat percent = NumberFormat.getPercentInstance();
    String display = "Discount Percent: " + percent.format(Customer);

    System.out.println(display);
}

// a method that accepts a CustomerType enumeration
public static double getDiscountPercent (CustomerType ct)
{
    double discountPercent = 0.0;
    if (ct == CustomerType.Retail)
        discountPercent = .10;
    else if (ct == CustomerType.College)
        discountPercent = .20;
    else if (ct == CustomerType.Trade)
        discountPercent = .30;

    return discountPercent;
}
}

这是我的枚举:

public enum CustomerType {
    Retail,Trade,College;
    public String toString() {
        String s = "";
        if (this.name() == "College")
        s = "College customer";
        return s;
    }
}

解决方法

枚举非常强大,可以将静态数据保存在一个地方.你可以这样做:

public enum CustomerType {

    Retail(.1,"Retail customer"),College(.2,"College customer"),Trade(.3,"Trade customer");

    private final double discountPercent;
    private final String description;

    private CustomerType(double discountPercent,String description) {
        this.discountPercent = discountPercent;
        this.description = description;
    }

    public double getDiscountPercent() {
        return discountPercent;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return description;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读