我有枚舉像下面如何從java中的值獲取枚舉構造函數名稱?
enum Car {
lamborghini("900"),tata("2"),audi("50"),fiat("15"),honda("12");
private String price;
Car(String p) {
price = p;
}
String getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
System.out.println(Car.valueOf("lamborghini").getPrice());
for (Car c : Car.values())
System.out.println(c + " costs "
+ c.getPrice() + " thousand dollars.");
}
}
這是工作正常,但我有一樣的輸入「900」,所以我想拿到enumConstructorName像蘭博基尼,我怎樣才能做到這一點。
的[將字符串轉換爲Java中的枚舉]可能的複製(http://stackoverflow.com/questions/604424/convert-a- string-to-an-enum-in-java) – wero
有沒有直接的方法來做到這一點。您必須遍歷每一個,並將您的輸入與價格進行比較。 – resueman
通過遍歷所有車輛,找到價格爲「900」的車輛。 –