/////////////////////////////////////////////////////////CURRENCY.JAVA//////////////////////////////////////////////////////////////////
//Akshat Shah
//IT 313
//Project 5
//Importing the scanner, dataset, chart, plot, url and exception.
import java.io.*;
import java.util.Scanner;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities;
import java.net.URL;
public class currency {
//Static method to get the targetcurrency(from the input file)
public static String getCurrency(Scanner s) throws IOException {
String targetCurrency = s.nextLine();
return targetCurrency;
}
//main method to call the method and run the print statements
public static void main(String[] args) throws IOException {
Scanner output = new Scanner(new File("currencies.txt"));
//Creating new dataset(Barchart)
DefaultCategoryDataset barChartDataset = new DefaultCategoryDataset();
//Using the while loop to call all the methods and print the exchangerate values
while(output.hasNextLine()){
String sourceCurrency = getCurrency(output);
String url = getURLString(sourceCurrency);
double exchangeRate = getExchangeRate(url);
System.out.println(exchangeRate);
barChartDataset.addValue(exchangeRate, "INR", sourceCurrency);
}
// Define JFreeChart object that creates line chart.
JFreeChart barChartObject = ChartFactory.createBarChart(
"Exchange Rates", "Currency codes", "1 EUR equals:", barChartDataset,
PlotOrientation.VERTICAL,
false, // Include legend.
false, // Include tooltips.
false); // Include URLs.
// Write line chart to a file.
int imageWidth = 640;
int imageHeight = 480;
File barChart = new File("exchangerate.png");
ChartUtilities.saveChartAsPNG(barChart, barChartObject, imageWidth, imageHeight);
}
//This method will allow to read from the web and output the values of the targetcurrency
public static double getExchangeRate(String urlString) throws IOException {
URL url = new URL(urlString);
Scanner s1 = new Scanner(url.openStream());
String jsonString = s1.nextLine();
System.out.println(jsonString);
int start = jsonString.indexOf("\"rates\":") + 15;
int end = jsonString.length() - 2;
String exchangeRate = jsonString.substring(start,end);
return Double.parseDouble(exchangeRate);
}
//Getting the url for the targetcurrency
public static String getURLString(String targetCurrency) throws FileNotFoundException {
String prefix = "http://data.fixer.io/api/latest";
String accessKey = "?access_key=e6dbd558da980cd848c0ebb36a9b6156";
String insert = "&symbols=";
String urlString = prefix + accessKey + insert + targetCurrency;
return urlString ;
}
}
#INPUT FILE
Currencies.txt
#OUTPUT FILE
ExchangeRate.png