Попытка прочитать формулу из текстового файла, сохранить строки формул, вычислить формулы и записать ответы в новый файл - PullRequest
0 голосов
/ 31 октября 2018

Здравствуйте, у меня проблема со следующим кодом: Он читает из текстового файла, который имеет следующее:

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

Я специально застрял в комментариях с объявлением об объявлении ArrayList для хранения токенизированной формулы из строки String и определении оператора и вычислении значения результата.

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());
 }
 }
}

Если бы кто-нибудь мог придумать код, который определяет эти комментарии, я был бы признателен за это!

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Этот код немного грязный, и он не избегает пробелов, но вот он.

import java.io.*;
import java.util.*;
public class ReadFromFile {
    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
                //toString("4 * 5".split("\\s+")
                // Declare ArrayList of for storing tokenized formula from String line
                ArrayList<String> formula = new ArrayList<String>();
                for (int i = 0; i < line.length(); i++)
                {
                    formula.add(String.valueOf(line.charAt(i)));
                }
                double result = 0; // The variable to store result of the operation
                // Determine the operator and calculate value of the result
                int firstNum = Integer.parseInt(formula.get(0));
                int secondNum = Integer.parseInt(formula.get(4));
                char operator = formula.get(2).charAt(0);
                result = (operator == '+' ? firstNum + secondNum
                        : operator == '-' ? firstNum - secondNum
                                : operator == '*' ? firstNum * secondNum
                                        : operator == '/' ? firstNum / secondNum : 0);
                System.out.println(formula.get(0) + ' ' + formula.get(2) + ' ' +
                        formula.get(4) + " = " + 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());
        }
    }
}
0 голосов
/ 31 октября 2018

Если вы намерены оценивать выражение построчно, тогда мы можем использовать ScriptEngine

Вы можете получить детали из этих сообщений

Я изменил ваш образец следующим образом. Пожалуйста, посмотрите на это.

public static void main(String[] args) {
    String line;
    Scanner input = null;
    PrintWriter output = null;
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    try {

        // open file for reading the calculated formulas "formulas.txt"
        input = new Scanner(
                new File("/Users/xxx/Downloads/formulas.txt"));
        // open file for storing the calculated formulas "results.txt"
        output = new PrintWriter(new File(
                "/Users/xxx/Downloads/results.txt"));

        // read one line at a time
        while (input.hasNextLine()) {
            line = input.nextLine();
            Object result = null;
            try {
                result = engine.eval(line);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            // Write result to file
            output.println(line + " = " + result);
        }
        // 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());
    }
}

вывод выглядит следующим образом

4 * 5 = 20
3 / 4 = 0.75
3 - 1 = 2
2 + 3 = 5
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...