如何在 Java 中將字串轉換為列舉?


Enum 類中的 valueOf() 方法接受字串值,並返回指定型別的列舉常量。

示例

我們建立一個名為 Vehicles 的列舉,它有 5 個常量,表示 5 輛不同滑板車的型號,其價格作為值,如下所示 −

enum Vehicles {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Vehicles(int price) {
      this.price = price;
   }
   //Static method to display the price
   public int getPrice(){
      return this.price;
   }
}

以下 Java 程式從使用者處接受字串值,使用 valueOf() 方法將其轉換為 Vehicles 型別的列舉常量,並顯示所選常量的值(價格)。

public class EnumerationExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]");
      System.out.println("Enter the name of required scoter: ");
      String name = sc.next();
      Vehicles v = Vehicles.valueOf(name.toUpperCase());
      System.out.println("Price: "+v.getPrice());
   }
}

輸出

Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]
Enter the name of required scoter:
activa125
Price: 80000

更新於: 2019-07-30

3K+ 檢視

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.