In: Computer Science
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
/**
* This program converts Dollars to Euros and Japanese Yen
* Firstly, it generates 10 random Dollar amounts between 10 and
500, and writes them to a .txt file
* Then, it reads from the .txt file and converts the amounts to
their respective Euro and Yen values
* @author USER
*/
public class CurrencyConverter {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the input filename: ");
String fileName = sc.nextLine().trim();
// generate 10 dollar amounts and write them to the file
generateDollarAmounts(fileName, 10);
System.out.println();
// read the dollars from file, line-by-line and display the euro
and yen values
readAndConvert(fileName);
}
private static void generateDollarAmounts(String fileName, int
n)
{
System.out.println("Generating " + n + " random dollar amounts and
writing them to " + fileName + "..");
FileWriter fw;
PrintWriter pw;
try {
fw = new FileWriter(new File(fileName));
pw = new PrintWriter(fw);
// generate 10 random values and write them to the file
for(int i = 0; i < n; i++)
{
if(i == n - 1)
pw.write(generateRandomValues() + "");
else
pw.write(generateRandomValues() + System.lineSeparator());
}
pw.flush();
fw.close();
pw.close();
System.out.println(n + " random dollar values generated and written
successfully!");
} catch (IOException ex) {
System.out.println("Error while writing dollars to file: " +
fileName);
System.exit(-1);
}
}
private static void readAndConvert(String fileName)
{
System.out.println("Reading the dollar amounts from " + fileName +
"..");
Scanner fileReader;
try
{
fileReader = new Scanner(new File(fileName));
while(fileReader.hasNextLine())
{
double dollarRead =
Double.parseDouble(fileReader.nextLine().trim());
System.out.println("$" + String.format("%.2f", dollarRead) + " =
"
+ String.format("%.2f", dollarToEuro(dollarRead)) + "
Euro.");
System.out.println("$" + String.format("%.2f", dollarRead) + " =
"
+ String.format("%.2f", dollarToYen(dollarRead)) + " Japanese
Yen.\n");
}
fileReader.close();
System.out.println("Exiting...");
}catch(FileNotFoundException fnfe){
System.out.println(fileName + " could not be found!");
System.exit(-1);
}
}
private static double generateRandomValues()
{
Random rand = new Random();
return(10 + (500 - 10) * rand.nextDouble());
}
private static double dollarToEuro(double dollar)
{
return(dollar * 0.91);
}
private static double dollarToYen(double dollar)
{
return(dollar * 108.64);
}
}
***************************************************************** SCREENSHOT **********************************************************