读文本计算表达式
【问题】
Java Reading Lines and Doing Math Equations
So I have this project to do, that I need to read a text file named Input, and I'm doing it like this:
public static void textParser() {
File inputFile = new File("Input.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String inputsText;
while ((inputsText = br.readLine()) != null) {
System.out.println(inputsText);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and it works. Inside of Input.txt, it shows:
6
10 + 4
12 - 3
1000 / 50
9 * 64
2^5
90 % 8
1 + 1
6 * 4
The first line (6) will always be the amount of equations to-do, can be different than 6. Then I have to do how many equations the first line says to, how would I go on doing that? Thanks!
别人的回答:
I have finally figured it out a different way that works, here is how I'm doing it:
public static void textParser() {
File inputFile = new File("Input.txt");
try {
Scanner scanner = new Scanner(inputFile);
int numberOfQuestions = Integer.parseInt(scanner.next());
for (int i = 1; i <= numberOfQuestions; i++) {
int firstInt = Integer.parseInt(scanner.next());
String operationSign = scanner.next();
int secondInt = Integer.parseInt(scanner.next());
if (operationSign.contains("+")) {
int answer = firstInt + secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " + " + secondInt + " = " + answer);
} else if (operationSign.contains("-")) {
int answer = firstInt - secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " - " + secondInt + " = " + answer);
} else if (operationSign.contains("/")) {
int answer = firstInt / secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " / " + secondInt + " = " + answer);
} else if (operationSign.contains("*")) {
int answer = firstInt * secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " * " + secondInt + " = " + answer);
} else if (operationSign.contains("%")) {
int answer = firstInt % secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " % " + secondInt + " = " + answer);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
【回答】
表达式解析和计算是个很麻烦的事,问题中的运算还算简单,可以硬写出来,如果再带有括号什么的,就太难写了。
这个问题可以用动态代码来解决,即让字符串变成可执行的代码,比如让“3*2.5”这个无法执行的字符串变成可执行的“float f=3*2.5;”。
JAVA其实是支持动态代码的,但使用的时候极其复杂。建议用SPL来做,可以直接读取文本文件完成这个计算:
A |
|
1 |
=file("D:\\Input.txt").read@n() |
2 |
=A1.(if(like(~,"*^*"),eval("power("+~.words@d().concat@c()+")"),eval(~))) |
A1:读取文本
A2:对序列A1循环动态解析表达式,一般的运算表达式,直接通过A1.(eval(~))动态解析即可,如果有特殊的表达式,就需要先处理成相应的SPL函数表达式,比如上面这个例子中的2^5,就需要先转换成power函数,再通过eval去动态解析
写好的脚本如何在应用程序中调用,可以参考Java 如何调用 SPL 脚本