Question: Read from a text file and use an array list to read data that you will use in a specified calculation. After the calculation is

Read from a text file and use an array list to read data that you will use in a specified calculation. After the calculation is made, you are to write the results to an output file.

Text file contents: 4,5 7,8 3,2

import java.io.*; import java.util.*; import javax.script.*; public class FileCalculator { String operator; ArrayList  lines = new ArrayList(); ArrayList  results = new ArrayList(); int [][] numbers; String inputPath; public FileCalculator(String path, String operator){ // populate object variables } public void readLineByLine(BufferedReader reader)throws IOException{ // create input string to check for null input from buffered reader // while the input from the buffered reader is not null // read the next line, add to lines // populate the numbers array with empty array of size lines.size(),2 } public void convertToArray(){ // go through each line from lines and split the string into two ints // populate the numbers array } public void calculate()throws ScriptException{ // if the operator is (*,+,-) // the script engine manager allows java to execute string as code // in this instance, the engine is for javascript code ScriptEngineManager scm = new ScriptEngineManager(); ScriptEngine jsEngine = scm.getEngineByName("JavaScript"); // for each row in numbers, evaluate using expression below this.results.add((Integer)jsEngine.eval(this.numbers[x][0]+this.operator+this.numbers[x][1])); // else, the operator is invalid, print that the operator is invalid } public void writeToFile()throws IOException{ String newFile = "answers.txt"; // create file from input path String parentDirectory = this.inputPath.substring(0,file.getAbsolutePath().lastIndexOf(File.separator)); String newPath = parentDirectory + "/" + newFile; System.out.println("Written to: " + newPath); // create BufferedWriter from newPath // for each result, write to file, append newline on each write // close writer } public static void main(String [] args)throws IOException{ // correct path for your pc String path = "path to text file"; try{ // create FileCalculator with path and operator // create FileReader from path // create BufferedReader from FileReader // execute line by line read // convert lines to array // calculate results // write to file }catch(FileNotFoundException ex) { System.out.println("Unable to open file '" + path + "'"); }catch(ScriptException ex) { System.out.println("Error executing operation"); } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!