当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Currency getInstance()用法及代码示例


Java中的getInstance()货币类方法用于检索给定货币代码的该货币实例。

用法:

CURRENCY.getInstance(String currency_code)

参数:此方法接受一个参数currency_code,它是特定货币的货币。


返回值:此方法返回用于货币代码的货币实例。

异常:如果调用了无效的代码,该方法将引发运行时错误。

以下示例程序旨在说明getInstance()方法的用法:

示例1:

// Java Code to illustrate getInstance() 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 
        System.out.println("Currency Code of India is: "
                           + curr_ency.toString()); 
    } 
}
输出:
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 
        System.out.println("Currency Code of USA is: "
                           + curr_ency.toString()); 
    } 
}
输出:
Currency Code of USA is: USD

示例3:输入无效的货币代码。

// Java Code to illustrate getInstance() 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


相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Currency getInstance() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。