Java Currency toString()方法及示例
Java中货币类的 toString() 方法用于检索该货币的货币代码,它实际上是字符串格式的官方ISO 4217货币代码。
语法
CURRENCY.toString()
参数: 此方法不接受任何参数。
返回值 :该方法返回货币的ISO 4217货币代码。
异常: 如果调用了一个无效的代码,该方法会抛出运行时错误。
下面的程序说明了toString()方法的工作。
程序 1 :
// Java Code to illustrate toString() method
import java.util.*;
public class Currency_Demo {
public static void main(String[] args)
{
// Creating a currency with the code
Currency curr_ency
= Currency.getInstance("INR");
// Getting the currency code
String currency_code
= curr_ency.toString();
System.out.println("Currency Code of India is: "
+ currency_code);
}
}
输出:
Currency Code of India is: INR
程序2
// Java Code to illustrate toString() method
import java.util.*;
public class Currency_Demo {
public static void main(String[] args)
{
// Creating a currency with the code
Currency curr_ency
= Currency.getInstance("USD");
// Getting the currency code
String currency_code
= curr_ency.toString();
System.out.println("Currency Code of USA is: "
+ currency_code);
}
}
输出:
Currency Code of USA is: USD
程序3: 对于一个无效的货币代码。
// Java Code to illustrate toString() method
import java.util.*;
public class Currency_Demo {
public static void main(String[] args)
{
try {
// Creating a currency with the code
Currency curr_ency = Currency.getInstance("USDA");
// Getting the currency code
String currency_code = curr_ency.toString();
System.out.println("Invalid Currency Code: "
+ currency_code);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IllegalArgumentException