2013-03-27 2 views
3

CustomerType 열거 형에 toString 메서드를 추가하고 싶습니다. 내 에 따라 달라지면 내 클래스는 System.out.println() 할인율 메시지를 반환합니다. 이는 고객 유형 대학이기 때문에 .20입니다. 열거 형을 처음 사용하고 고객 유형에 따라 "대학 고객"을 인쇄하는 열거 형에 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; 
    } 
} 
+2

무엇이 오류입니까? – brandonsbarber

+0

한눈에이 코드가 잘 보입니다. – Armand

답변

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

} 
+0

+1 자바 열거 형의 힘을 보여주기 위해 :) – Patashu

+0

Java 상수가 모두 대문자라는 규칙을 따르지 않아서 고마워. 이로써 이것을 자신의 일로 제출 한 학생들을 쉽게 잡을 수있게되었습니다. –

관련 문제