게으른 개발자의 끄적거림

Java 환율 계산(int형을 달러, 원으로 환산)

끄적잉 2024. 5. 20. 22:21
반응형

Java에서 정수형(int)을 원으로 환산하는 방법에 대해 자세히 설명하겠습니다. 이 과정은 몇 가지 주요 단계를 포함하며, 각 단계는 코딩과 논리적 사고를 요구합니다. 다음은 전체적인 과정을 설명하는 단계별 가이드입니다.

 


### 1. 기초 개념 이해하기

#### 1.1. 정수형(int)의 특성
Java에서 `int` 타입은 32비트 정수형으로, -2,147,483,648부터 2,147,483,647까지의 값을 가질 수 있습니다. 정수형은 소수점 이하의 값을 포함하지 않기 때문에, 원화 금액을 정수형으로 표현하는 데 적합합니다.

 


#### 1.2. 환율 정보 획득
환율은 변동이 있으며, 실시간으로 업데이트됩니다. 환율 정보를 얻기 위해 외부 API를 사용할 수 있습니다. 예를 들어, 외환거래 API 또는 금융 데이터 제공 사이트를 통해 실시간 환율 정보를 가져올 수 있습니다.

 

 

### 2. 환율 정보 가져오기

#### 2.1. 외부 API 사용하기
환율 정보를 얻기 위해 외부 API를 사용해야 합니다. 대표적인 환율 API로는 Open Exchange Rates, CurrencyLayer, 그리고 fixer.io 등이 있습니다. 다음은 fixer.io API를 사용하는 예제입니다.

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class CurrencyConverter {
    private static final String ACCESS_KEY = "YOUR_ACCESS_KEY";
    private static final String API_URL = "http://data.fixer.io/api/latest?access_key=" + ACCESS_KEY;

    public static double getExchangeRate(String fromCurrency, String toCurrency) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        
        in.close();
        connection.disconnect();
        
        JSONObject json = new JSONObject(content.toString());
        JSONObject rates = json.getJSONObject("rates");
        
        double fromRate = rates.getDouble(fromCurrency);
        double toRate = rates.getDouble(toCurrency);
        
        return toRate / fromRate;
    }

    public static void main(String[] args) {
        try {
            double rate = getExchangeRate("USD", "KRW");
            System.out.println("Exchange Rate (USD to KRW): " + rate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

위의 코드에서는 fixer.io API를 사용하여 USD에서 KRW로 변환하는 환율을 가져오는 방법을 보여줍니다. `ACCESS_KEY`는 fixer.io에서 제공하는 API 키로, 실제 키로 대체해야 합니다.

 

반응형

 


### 3. 정수형 금액을 원으로 변환하기

#### 3.1. 금액 변환 함수 구현하기
환율 정보를 바탕으로 특정 금액을 다른 통화로 변환하는 함수를 구현할 수 있습니다. 다음은 USD 금액을 KRW로 변환하는 예제입니다.

```java
public class CurrencyConverter {
    // 환율 정보를 가져오는 메서드 (앞서 설명한 코드 사용)
    public static double getExchangeRate(String fromCurrency, String toCurrency) throws Exception {
        // ... (이전 코드와 동일)
    }
    
    // 정수형 금액을 원화로 변환하는 메서드
    public static int convertToWon(int amountInUSD) throws Exception {
        double exchangeRate = getExchangeRate("USD", "KRW");
        return (int)(amountInUSD * exchangeRate);
    }

    public static void main(String[] args) {
        try {
            int amountInUSD = 100; // 변환할 금액 (USD)
            int amountInKRW = convertToWon(amountInUSD);
            System.out.println("Amount in KRW: " + amountInKRW);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

위의 예제에서는 100 USD를 원화로 변환하는 과정을 보여줍니다. `convertToWon` 메서드는 주어진 USD 금액을 환율을 이용해 원화로 변환합니다.

 

 

 


### 4. 예외 처리 및 유효성 검증

환율 변환 과정에서 다양한 예외 상황이 발생할 수 있습니다. 예를 들어, 네트워크 오류, API 호출 실패, 유효하지 않은 통화 코드 등이 있습니다. 이러한 예외 상황을 적절히 처리하는 것이 중요합니다.

#### 4.1. 예외 처리
다음은 예외 처리를 추가한 코드 예제입니다.

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class CurrencyConverter {
    private static final String ACCESS_KEY = "YOUR_ACCESS_KEY";
    private static final String API_URL = "http://data.fixer.io/api/latest?access_key=" + ACCESS_KEY;

    public static double getExchangeRate(String fromCurrency, String toCurrency) throws Exception {
        try {
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int status = connection.getResponseCode();
            if (status != 200) {
                throw new Exception("Failed to get response from API");
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            in.close();
            connection.disconnect();

            JSONObject json = new JSONObject(content.toString());
            if (!json.getBoolean("success")) {
                throw new Exception("API request was not successful");
            }

            JSONObject rates = json.getJSONObject("rates");

            if (!rates.has(fromCurrency) || !rates.has(toCurrency)) {
                throw new Exception("Invalid currency code");
            }

            double fromRate = rates.getDouble(fromCurrency);
            double toRate = rates.getDouble(toCurrency);

            return toRate / fromRate;
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            throw e;
        }
    }

    public static int convertToWon(int amountInUSD) throws Exception {
        try {
            double exchangeRate = getExchangeRate("USD", "KRW");
            return (int)(amountInUSD * exchangeRate);
        } catch (Exception e) {
            System.err.println("Conversion failed: " + e.getMessage());
            throw e;
        }
    }

    public static void main(String[] args) {
        try {
            int amountInUSD = 100;
            int amountInKRW = convertToWon(amountInUSD);
            System.out.println("Amount in KRW: " + amountInKRW);
        } catch (Exception e) {
            System.err.println("Main process failed: " + e.getMessage());
        }
    }
}
```

위의 코드에서는 API 응답 실패, 잘못된 통화 코드 등의 예외 상황을 처리합니다. 예외가 발생할 경우 오류 메시지를 출력하고 예외를 다시 던집니다.


반응형