3

我想在我的枚举中添加一个toString方法。如果取决于我现在是 0.20,CustomerType我的班级会返回折扣百分比消息,因为它是 customerType 大学。我是枚举的新手,我希望能够向我的枚举添加一个方法,根据客户类型打印“College customer”。实现这一点有困难吗?我到底做错了什么?System.out.println()cutomerTypetoString

听听我的课:

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

1 回答 1

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

}
于 2013-03-27T05:11:39.880 回答