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
  • 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 -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 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 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...

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • How to write a Java file out that that reads from numbers.txt with these numbers 2...

    How to write a Java file out that that reads from numbers.txt with these numbers 2 6 7 9 5 4 3 8 0 1 6 8 2 3 and write to a file called totalSum.txt that looks like: 2+6+7+9=24 and so on using this code import java.io.*; import java.util.Scanner; public class FileScanner {    public static void main(String[] args)    {        /* For Homework! Tokens*/        Scanner file = null;        PrintWriter fout= null;   ...

  • 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...

  • Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File;...

    Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Lab8Num1 { public static void main(String[] args) { //Declaring variable to be used for storing and for output double biggest,temp; //Creating file to read numbers File inFile = new File("lab8.txt"); //Stream to read data from file Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { //Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex); } //get first number...

  • Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this...

    Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this file, include your assignment documentation code block. After the documentation block, you will need several import statements. import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; Next, declare the Lab12 class and define the main function. public class Lab12 { public static void main (String [] args) { Step 2: Declaring Variables For this section of the lab, you will need to declare...

  • 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...

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
ADVERTISEMENT