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?
From the javadocs, there is a method that can be used to do this.
ie
As a random side note, I almost always add an
iValueOf
(ie, a case insensitive version) method to my enums, for ease of use.