2014-11-04 143 views
3

我有一个ISO 4217的数字货币代码:840转换成ISO 4217的数字货币代码货币名称

我想要得到的货币名称:美元

我试图做到这一点:

Currency curr1 = Currency.getInstance(“840”);

但我不断收到java.lang.IllegalArgumentException异常

如何解决?有任何想法吗?

+0

您必须提供'Locale'。 – Hannes 2014-11-04 12:04:35

+0

我还可以提供一个字符串:getInstance(String currencyCode) 返回给定货币代码的Currency实例。 – 2014-11-04 12:12:50

+0

我可以从数字代码中获取语言环境吗? – 2014-11-04 12:13:19

回答

2

java.util.Currency.getInstance仅支持ISO 4217货币代码,而非货币编号。但是,您可以使用getAvailableCurrencies方法检索所有币种,然后通过比较getNumericCode方法的结果来搜索代码为840的币种。

像这样:

public static Currency getCurrencyInstance(int numericCode) { 
    Set<Currency> currencies = Currency.getAvailableCurrencies(); 
    for (Currency currency : currencies) { 
     if (currency.getNumericCode() == numericCode) { 
      return currency; 
     } 
    } 
    throw new IllegalArgumentException("Currency with numeric code " + numericCode + " not found"); 
} 
0

你必须提供如 “USD” 的代码,然后将返回的Currency对象。如果您使用的是JDK 7,那么您可以使用以下代码。 JDK 7有一个方法getAvailableCurrencies()

public static Currency getCurrencyByCode(int code) { 
    for(Currency currency : Currency.getAvailableCurrencies()) { 
     if(currency.getNumericCode() == code) { 
      return currency; 
     } 
    } 
    throw new IllegalArgumentException("Unkown currency code: " + code); 
}