Question

Please write this in Java, please write comments as you create it, and please follow the...

  • Please write this in Java, please write comments as you create it, and please follow the coding instructions.
  • As you are working on this project, add print statements or use the debugger to help you verify what is happening. Write and test the project one line at a time.
  • Before you try to obtain currency exchange rates, obtain your free 32 character access code from this website:
    https://fixer.io/
     Here's the code:  46f27e9668fcdde486f016eee24c554c
  • Choose five international source currencies to monitor. Each currency is referenced with a three letter ISO 4217 currency code. For example, the code for the British Pounds is GBP. " Place these currency codes in a text file named currency.txt.
  • Use these codes: Colombian Peso: COP: 3540 .250862, Costa Rican Colon CRC: 685.938731, Egyptian Pound EGP: 19.758935, Jamaican Dollar JMD: 150.549578, and Yen JPY: 124.536082 place them in a file called currency.text​​​​​
  • Use try..catch blocks to handle all exceptions with a user-friendly messages in the catch blocks. Do not throw any exceptions.
  • In a while loop that terminates when the end of file is reached, do the following:
    1. Read the next currency from the currencies.txt file.
    2. Create a URL for the fixer.io site that will obtain a URL for obtaining the exchange rate using the currency read in Step 1 as the target currency (symbol) and EUR as the source currency (base). Which you code:
      http://data.fixer.io/api/latest​​​​​​
      ? access_key = 46f27e9668fcdde486f016eee24c554c or YOUR_ACCESS_KEY instead of the code itself, one of them should work
        & symbols = COP,CRC,EGP,JMD,JPY
    3. Using the URL from Step 2, create a scanner object that reads the JSON string from the website. Extract the exchange rate from the JSON string.
    4. Add a bar to a JFreeChart bar chart, whose height is the exchange rate from Step 3. This is the bar chart example:
      // JAR files jcommon-1.0.23.jar and jfreechart-1.0.19.jar 
      // must be added to project.
      
      import java.io.*;
      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; 
      public class BarChart {  
          public static void main(String[] args) {
              try {
                     
                  // Define data for line chart.
                  DefaultCategoryDataset barChartDataset = 
                      new DefaultCategoryDataset();
                  barChartDataset.addValue(1435, "total", "East");
                  barChartDataset.addValue(978,  "total", "North");
                  barChartDataset.addValue(775,  "total", "South");                
                  barChartDataset.addValue(1659, "total", "West");                
                      
                  // Define JFreeChart object that creates line chart.
                  JFreeChart barChartObject = ChartFactory.createBarChart(
                      "Sales ($1000)", "Region", "Sales", 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("sales.png");              
                   ChartUtilities.saveChartAsPNG(
                       barChart, barChartObject, imageWidth, imageHeight); 
              }
            
              catch (Exception i)
              {
                  System.out.println(i);
              }
          }
      }

    Identify the source code items that belong before, in, and after the while loop.
  • Don't forget to close each scanner when you are finished using it.
  • Your project should contain only a single class, which contains the main method. This class must define at least three additional static methods that modularize the tasks in this project. For example, you might define methods such as these:
    public static String getCurrency(Scanner s)
    public static String getUrlString(String targetCurrency)
    public static double getExchangeRate(String urlString)
    
    If you wish, use the Eclipse Refactor capability to extract the methods.
  • Here is suggested pseudocode for the whole project. You can get this to work first and then extract the methods, either by hand or using Eclipse Refactor:
    create File object for currencies.txt
    create scanner1 to read from input file
    create new DefaultCategoryDataset object to 
        contain bars for histogram
    while more lines in input file
        read target currency using scanner1
        construct URL for obtaining target exchange rate
        create scanner2 from URL
        use URL to obtain JSON string
        extract target exchange rate from JSON string
        add histogram bar representing target 
            exchange rate to DefaultCategoryDataset object
        close scanner2
    end while
    create a bar chart object from DefaultCategoryDataset
        object
    create graphics image file
    close scanner1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

package HomeworkLib;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

public class Barcha {

   public static void main(String[] args) throws MalformedURLException, IOException{
           

       Scanner s = new Scanner(new File("currencies.txt"));
       double[] b = new double[5];
       // loop to determine currency values based on currencies.txt
        for(int i=0; s.hasNextLine( );i++) {
            String sourceCurrency = getCurrency(s);
            String url = getURLString(sourceCurrency);
            double exchangeRate = getExchangeRate(url);
            System.out.println(exchangeRate);
            //assigns each exchangerate value into an array
            b[i]= exchangeRate;
        }
        s.close( );
   // Define data for barchart.
        DefaultCategoryDataset barChartDataset = new DefaultCategoryDataset();
      
        //bar for Swiss Franc
        barChartDataset.addValue(b[0], "total", "CHF");
        //bar for Nigerian Naira
        barChartDataset.addValue(b[1], "total", "NGN");
      
        //United Arab Emirates dirham
        barChartDataset.addValue(b[2], "total", "AED");
        //Lebanise pounds
        barChartDataset.addValue(b[3], "total", "LBP");
        //British pounds
        barChartDataset.addValue(b[4], "total", "GBP");  
        // Define JFreeChart object that creates line chart.
        JFreeChart barChartObject = ChartFactory.createBarChart(
            "Value", "Name of Currencies", "USD", 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("sales.png");            
         ChartUtilities.saveChartAsPNG(
             barChart, barChartObject, imageWidth, imageHeight);
      
   }

   private static double getExchangeRate(String url) throws IOException, MalformedURLException {
       //Scanner to find URL input and open it
       Scanner fromWeb = new Scanner((new URL(url)).openStream( ));
       String line = fromWeb.nextLine( );
       fromWeb.close( );
       //splits exchangeRate
       double exchangeRate = Double.parseDouble(line.split(",")[1]);
       return exchangeRate;
   }

   private static String getCurrency(Scanner s) {
       //reads from scanner in main method to determine if there's a nextline available
       String sourceCurrency = s.nextLine( );
       return sourceCurrency;
   }

   private static String getURLString(String sourceCurrency) {
       //Uses Suffix and prefix to find and calculate currency value
       //compared with the target currency
       String prefix = "http://download.finance.yahoo.com/d/quotes.csv?s=";
       String suffix = "=X&f=sl1d1t1ba&e=.csv";
       String targetCurrency = "USD";
       String url = prefix + sourceCurrency + targetCurrency + suffix;
       return url;
   }  

}

Add a comment
Know the answer?
Add Answer to:
Please write this in Java, please write comments as you create it, and please follow the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java : Please help me correct my code: create a single class (Program11.java) with a main...

    Java : Please help me correct my code: create a single class (Program11.java) with a main method and some auxiliary methods to input a 2-D array from a disk file, input some “transactions” to change the 2-D array and output the changed 2-D array to another file. Your main method will be minimal (see below). Most of the work will go on in your methods. In main, declare (but do not instantiate) 2-D array. Then call the three methods. The...

  • read the code and comments, and fix the program by INSERTING the missing code in Java...

    read the code and comments, and fix the program by INSERTING the missing code in Java THank you please import java.util.Scanner; public class ExtractNames { // Extract (and print to standard output) the first and last names in "Last, First" (read from standard input). public static void main(String[] args) { // Set up a Scanner object for reading input from the user (keyboard). Scanner scan = new Scanner (System.in); // Read a full name from the user as "Last, First"....

  • JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out...

    JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out the name of the student with the lowestgpa. In the attached zip file, you will find two files HighestGPA.java and students.dat. Students.dat file contains names of students and their gpa. Check if the code runs correctly in BlueJ or any other IDE by running the code. Modify the data to include few more students and their gpa. import java.util.*; // for the Scanner class...

  • Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

    Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method: public abstract Product get(String productCode); Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this: IProductDB db...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • Write a Java method that will take an array of integers of size n and shift...

    Write a Java method that will take an array of integers of size n and shift right by m places, where n > m. You should read your inputs from a file and write your outputs to another file. Create at least 3 test cases and report their output. I've created a program to read and write to separate files but i don't know how to store the numbers from the input file into an array and then store the...

  • Java Write a pair of serialization / deserialization apps that create a user’s Car list, w/...

    Java Write a pair of serialization / deserialization apps that create a user’s Car list, w/ a class named Car, which includes model, VINumber (int), and CarMake (an enum, with valid values FORD, GM, TOYOTA, and HONDA) as fields. Use an array similar to the way the SerializeObjects did to handle several BankAccounts. Your app must include appropriate Exception Handling via try catch blocks (what if the file is not found, or the user inputs characters instead of digits for...

  • JAVA Modify the code to create a class called box, wherein you find the area. I...

    JAVA Modify the code to create a class called box, wherein you find the area. I have the code in rectangle and needs to change it to box. Here is my code. Rectangle.java public class Rectangle { private int length; private int width;       public void setRectangle(int length, int width) { this.length = length; this.width = width; } public int area() { return this.length * this.width; } } // CONSOLE / MAIN import java.awt.Rectangle; import java.util.Scanner; public class Console...

  • Really need help with this. This is for my Advanced Java Programming Class. If anyone is...

    Really need help with this. This is for my Advanced Java Programming Class. If anyone is an expert in Java I would very much appreciate the help. I will provide the code I was told to open. Exercise 13-3   Use JPA to work with the library checkout system In this exercise, you'll convert the application from the previous exercise to use JPA instead of JDBC to access the database. Review the project Start NetBeans and open the project named ch13_ex3_library that's...

  • I have the files set up in the write place. I am just confused on how...

    I have the files set up in the write place. I am just confused on how to use some of the desire methods to execute this code. // Copy text file and insert line numbers Create a NetBeans project named AddLineNumbers following the instructions provided in the Starting a NetBeans Project instructions in the Programming Exercises/Projects Menu on Blackboard. After you have created your NetBeans project AddLineNumbers and before you attempt to execute your application download and/or copy the text...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT