Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Your task is to read a file containing arithmetic instructions such as Each inst

ID: 3759999 • Letter: Y

Question

Your task is to read a file containing arithmetic instructions such as

Each instruction contains an integer, an operator (+, -, or *), and another integer.

Return an array list of the results. If there is any error, throw an IOException.

Complete the following file:

Arithmetic.java

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

public class Arithmetic

{

/**

This class reads a file containing arithmetic expressions and returns an

array list of the results.

@param filename the file name

@return a list of results

*/

public static ArrayList<Integer> read(String filename) throws IOException

{

ArrayList<Integer> list = new ArrayList<>();

Scanner scanner = new Scanner(new File(filename));

while(scanner.hasNextInt()){

list.add(scanner.nextInt());

}

return list;

}


// This method checks your work. Do not touch it.

public static String check(String filename)

{

try

{

return read(filename).toString();

}

catch (IOException ex)

{

return "I/O exception thrown";

}

catch (Exception ex)

{

return ex.getClass().getName();

}

}

}

Explanation / Answer

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Arithmetic {
   /**
   * This class reads a file containing arithmetic expressions and returns an
   * array list of the results.
   *
   * @param filename
   * the file name
   * @return a list of results
   */
   public static ArrayList<Integer> read(String filename) throws IOException, ScriptException {
       ArrayList<Integer> list = new ArrayList<>();
       ScriptEngineManager mgr = new ScriptEngineManager();
   ScriptEngine engine = mgr.getEngineByName("JavaScript");
       Scanner scanner = new Scanner(new File(filename));
       while (scanner.hasNext()) {
           list.add((Integer) engine.eval(scanner.next()));
       }
       return list;
   }

   // This method checks your work. Do not touch it.
   public static String check(String filename) {
       try {
           return read(filename).toString();
       } catch (IOException ex) {
           return "I/O exception thrown";
       } catch (Exception ex) {
           return ex.getClass().getName();
       }
   }
}