【问题标题】: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尝试从文本文件中读取公式、存储公式行、计算公式并将答案写入新文件
【发布时间】:2018-10-31 03:48:50
【问题描述】:

您好,下面的代码有问题: 它从具有以下内容的文本文件中读取:

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

我特别卡在说 Declare ArrayList of for storage 来自字符串行的标记化公式和确定运算符并计算结果值的 cmets 上。

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

如果有人能提出确定这些 cmets 的代码,我将不胜感激!

【问题讨论】:

  • 这里有一个提示:System.out.println(Arrays.toString("4 * 5".split("\\s+"))).

标签: java arrays if-statement


【解决方案1】:

如果您打算逐行评估表达式,那么我们可以使用ScriptEngine

您可以从these post获取详细信息

我将您的示例修改如下。请看一下。

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

【讨论】:

    【解决方案2】:

    这段代码有点乱,也没有避免空格,但就是这样。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多