當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。