gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:02:45 24 4
gpt4 key购买 nike

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

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

49+62*61-364/64(53+26)0*7221-85+75-8590*76-50+6746*89-1534/83-3820/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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com