如何将 at switch 语句的字符串转换为枚举?
我有这样的代码,我想接受命令行 args fx "12 EUR" 进行转换:
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 conversion the StringcurrencyIn to enum so I can use the args input in the switch statements?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 javadocs 中,有一个可以用来执行此操作的方法。
即
作为随机旁注,我几乎总是向我的枚举添加一个 iValueOf(即不区分大小写的版本)方法,以便于使用。
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.