在Java中,如何使用enum&switch語句?
此範例顯示如何使用switch
語句檢查選擇哪個列舉成員。
package com.yiibai;
enum Car {
lamborghini, tata, audi, fiat, honda
}
public class UseOfEnumSwitch {
public static void main(String args[]) {
Car c;
c = Car.audi;
switch (c) {
case lamborghini:
System.out.println("You choose lamborghini!");
break;
case tata:
System.out.println("You choose tata!");
break;
case audi:
System.out.println("You choose audi!");
break;
case fiat:
System.out.println("You choose fiat!");
break;
case honda:
System.out.println("You choose honda!");
break;
default:
System.out.println("I don't know your car.");
break;
}
}
}
執行上面範例程式碼,得到以下結果 -
You choose audi!