3

列挙にtoStringメソッドを追加したいと思います。CustomerType私のクラスは、customerTypeカレッジであるため、現在.2​​0であるSystem.out.println()私に依存する場合、割引率メッセージを返します。私は列挙型を初めて使用しますが、顧客のタイプに応じて「Collegecustomer」を出力cutomerTypeするメソッドを列挙型に追加できるようにしたいと考えています。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;
    }
}
4

1 に答える 1

7

列挙型は、静的データを1か所に保持するために非常に強力です。あなたはそのようなことをすることができます:

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 に答える