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

时间:2013-03-27 05:03:37

标签: java

我想在toString枚举中添加CustomerType方法。如果取决于我现在.20的System.out.println(),我的班级会返回cutomerType折扣百分比消息,因为它是customerType college。我是枚举的新手,我希望能够在我的枚举中添加toString方法,根据客户类型打印“大学客户”。我在完成这个方面遇到了一些麻烦?我究竟做错了什么?

听到我的班级:

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 application\n");

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

1 个答案:

答案 0 :(得分:7)

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

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

}