Write a code in Java. Your task is to read a file containing arithmetic instruct
ID: 3860742 • Letter: W
Question
Write a code in Java. 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.
**Please do this without BufferedReader and ScriptManager. Only insert code in the bold area. Thank you!!
Complete the following code:
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
{
. . . //ONLY PUT CODE HERE
}
// 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
The function read does :
Program Coding:
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
*/
/** read method for reading the operation from file and returns the list
*/
public static ArrayList<Integer> read(String filename) throws IOException
{
try {
// reads the file
Scanner input = new Scanner(filename);
// s2 for reading the tokens
Scanner s2 = null;
File file = new File(input.nextLine());
input = new Scanner(file);
// declaring list
ArrayList<Integer> list = new ArrayList<>();//Creating arraylist
//for reading a line till the EOF
while (input.hasNextLine()) {
s2 = new Scanner(input.nextLine());
int s = Integer.parseInt(s2.next());
String s1 = s2.next();
int st = Integer.parseInt(s2.next());
// arthimetic opertaion
switch (s1){
case "+":
list.add(s+st);
break;
case "-":
list.add((s-st));
break;
case "*":
list.add((s*st));
break;
case "/":
list.add((s/st));
break;
}
}
input.close();
return(list);
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 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();
}
}
}
thank you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.