mardi 30 octobre 2018

Trying to read a formula from a text file, store the lines of formulas, calculate the formulas, and write the answers to a new file

Hello I am having trouble the following code: It reads from a text file that has the following:

4 * 5
3 / 4
3 - 1
2 + 3

I am specifically stuck on the comments that says Declare ArrayList of for storing tokenized formula from String line and Determine the operator and calculate value of the result.

import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
 public static void main(String[] args) throws FileNotFoundException {
 String line;
 Scanner input = null;
 PrintWriter output = null;

 try {

 //open file for reading the calculated formulas "formulas.txt"
 input = new Scanner(new File("C:\\formulas.txt"));
 //open file for storing the calculated formulas "results.txt"
 output = new PrintWriter(new File("C:\\results.txt"));

 // read one line at a time 
 while( input.hasNextLine()) {
 line = input.nextLine();

 System.out.println("read <" + line + ">"); // Display message to commandline
 // Declare ArrayList of for storing tokenized formula from String line

 double result = 0; // The variable to store result of the operation
 // Determine the operator and calculate value of the result
 System.out.println(formula.get(0) + ' ' + formula.get(1) + ' ' +
 formula.get(2) + " = " + result); // Display result to command line
 // Write result to file
 output.println("Print result of " + line + " to Results.txt");
 }
 // Need to close input and output files

 input.close();
 output.close();

 }
 catch (FileNotFoundException e) {
 // Display meaningful error message
  System.out.println("File Not Found: " + e.getMessage());
 }
 }
}

If anyone could come up with the code that determines these comments I would appreciate it!

Aucun commentaire:

Enregistrer un commentaire