How do I convert String to enum for at switch stat

2019-07-22 14:54发布

I have this code where I want to accept command line args fx "12 EUR" to do a conversion:

public class Main {

   enum Currency {EUR, USD, GBP,INVALID_CURRENCY;
   static final float C_EUR_TO_DKK_RATE = (float) 7.44;
   static final float C_USD_TO_DKK_RATE = (float) 5.11;
   static final float C_GBP_TO_DKK_RATE = (float) 8.44;
   static float result = 0;
   static int amount = 0;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Q1

        if (args.length == 2) {
            amount = Integer.parseInt(args[0]);
            String currencyIn = args[1].toString();

            Currency enumConversion = currencyIn; //**<---- HERE**
            switch (enumConversion) {
                case EUR:
                    result = amount * C_EUR_TO_DKK_RATE;
                    break;
                case USD:
                    result = amount * C_USD_TO_DKK_RATE;
                    break;
                case GBP:
                    result = amount * C_GBP_TO_DKK_RATE;
                    break;
                default:
                    result = 0;
                    break;
            }
            System.out.println((float) amount + " " + enumConversion + " converts to "
                + Math.round(result*100.0)/100.0 + " DKK");


        } else {
            System.out.println("Invalid arguments!");
            System.exit(1);
        }
    }

}
   }

How do I convert the String currencyIn to enum so I can use the args input in the switch statement?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-22 15:41
public Currency fromString(String s){
  try
  {
    return Currency.valueOf(s)
  }
  catch(IllegalArgumentException e)
  { 
    return null;
  }
}
查看更多
放荡不羁爱自由
3楼-- · 2019-07-22 15:58

From the javadocs, there is a method that can be used to do this.

static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

ie

Currency enumConversion = Currency .valueOf(currencyIn); //**<---- HERE**

As a random side note, I almost always add an iValueOf (ie, a case insensitive version) method to my enums, for ease of use.

查看更多
登录 后发表回答