java - 从文件中读入时如何使用字符串分词器?

标签 java calculator

我正在用 Java 实现一个 RPN 计算器,需要帮助创建一个类来将方程式解析为单独的标记。

我的输入文件将包含未知数量的方程式,如下所示:

49+62*61-36
4/64
(53+26)
0*72
21-85+75-85
90*76-50+67
46*89-15
34/83-38
20/76/14+92-15

I have already implemented my own generic stack class to be used in the program, but I am now trying to figure out how to read data from the input file. Any help appreciated.

I've posted the source code for my stack class at PasteBin, in case it may help.

I have also uploaded the Calculator with no filereading to PasteBin to show what I have done already.

I have now managed to get the file read in and the tokens broken up thanks for the help. I am getting an error when it reaches the end of the file and was wondering how to solve that?

Here is the code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

 public class TestClass {    
  static public void main(String[] args) throws IOException {
 File file = new File("testEquations.txt");
  String[] lines = new String[10];
  try {
    FileReader reader = new FileReader(file);
    BufferedReader buffReader = new BufferedReader(reader);
    int x = 0;
    String s;
    while((s = buffReader.readLine()) != null){
        lines[x] = s;
        x++;
    }
 }
  catch(IOException e){
    System.exit(0);
}
String OPERATORS = "+-*/()";

for (String st : lines) {
    StringTokenizer tokens = new StringTokenizer(st, OPERATORS, true);
    while (tokens.hasMoreTokens()) {
        String token = tokens.nextToken();
        if (OPERATORS.contains(token))
            handleOperator(token);
        else
            handleNumber(token);
    }
     }
   }

private static void handleNumber(String token) {
System.out.println(""+token);

   }

 private static void handleOperator(String token) {
System.out.println(""+token);

  }
  }

另外,我如何确保 RPN 逐行工作?我对尝试遵循的算法感到非常困惑。

最佳答案

因为所有运算符都是单个字符,您可以指示 StringTokenizer 将它们与数字标记一起返回。

String OPERATORS = "+-*/()";
String[] lines = ...

for (String line : lines) {
    StringTokenizer tokens = new StringTokenizer(line, OPERATORS, true);
    while (tokens.hasMoreTOkens()) {
        String token = tokens.nextToken();
        if (OPERATORS.contains(token))
            handleOperator(token);
        else
            handleNumber(token);
    }
}

关于java - 从文件中读入时如何使用字符串分词器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432094/

相关文章:

java - 在正文异常 spring rest 中添加新字段

javascript - 尝试使用从 JS 文本框中检索的数字进行计算时收到 NaN

java - 在 Java 中制作退格按钮,删除 Textview 中的最后一个字符

functional-programming - 如何在 Scheme 中仅使用 1 个列表来构建 2 个列表?

java - Apache poi 文件损坏且无法写入现有工作簿

java - DateTimeParseException : Text '2019-08-13T07:29:12.000+0000' could not be parsed, 在索引 23 处找到未解析的文本

java - 计算有障碍物的网格中的路径和我的分析

Java 类型转换问题

java - 使用 Java swing GUI 的形状计算器

java - 修改我的java swing计算器的图形