April 26, 2020
Estimated Post Reading Time ~

Currency converter service

I am attaching a simple program about, How to write Simple Currency Converter using Java Program. The program was written using Fixer Currency Converter Webservice. In this example, I am using Gson 2.8.0 API to convert JSON to Object in Java. you can download API from here.

CurrencyConversionResponse.java
package com.kishore.generic;

import java.util.Map;
import java.util.TreeMap;

public class CurrencyConversionResponse {
    private String base;
    private String date;

    private Map<String, String> rates = new TreeMap<String, String>();

    public Map<String, String> getRates() {
        return rates;
    }

    public void setRates(Map<String, String> rates) {
        this.rates = rates;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}

CurrencyConvertor.java
package com.kishore.generic;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import com.google.gson.Gson;
public class CurrencyConvertor {
    // API Provider URL
    private static final String API_PROVDIER = "http://api.fixer.io/";
    public static double convert(String fromCurrencyCode, String toCurrencyCode) {
        if ((fromCurrencyCode != null && !fromCurrencyCode.isEmpty())
                && (toCurrencyCode != null && !toCurrencyCode.isEmpty())) {
            CurrencyConversionResponse response = getResponse(API_PROVDIER
                    + "/latest?base=" + fromCurrencyCode);
            if (response != null) {
                String rate = response.getRates().get(toCurrencyCode);
                double conversionRate = Double.valueOf((rate != null) ? rate: "0.0");
                return conversionRate;
            }
        }
        return 0.0;
    }

    // Method to get the response from API
    private static CurrencyConversionResponse getResponse(String strUrl) {
        CurrencyConversionResponse response = null;
        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer();
        if (strUrl == null || strUrl.isEmpty()) {
            System.out.println("Application Error");
            return null;
        }

        URL url;
        try {
            url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            InputStream stream = connection.getInputStream();
            int data = stream.read();
            while (data != -1) {
                sb.append((char) data);
                data = stream.read();
            }
            stream.close();
            response = gson.fromJson(sb.toString(),
                    CurrencyConversionResponse.class);
        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("What is your currency code ?");
        String fromCurrencyCode = scanner.next();

        System.out.println("Enter the Amount :");
        double amount = scanner.nextDouble();

        System.out
                .println("Enter the Currency Code that you want to covert : ");
        String toCurrencyCode = scanner.next();

        fromCurrencyCode = fromCurrencyCode.toUpperCase();
        toCurrencyCode = toCurrencyCode.toUpperCase();

        // Currency Conversion
        double coversionRate = convert(fromCurrencyCode, toCurrencyCode);

        System.out.println("Hi, The " + amount + " " + fromCurrencyCode
                + " is equivalent to " + (coversionRate * amount) + " "
                + toCurrencyCode + " today.");
        scanner.close();
    }
}

Output
What is your currency code?
USD
Enter the Amount :
1
Enter the Currency Code that you want to covert : 
GBP
Hi, The 1.0 USD is equivalent to 0.77341 GBP today.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.