读文本计算表达式

【问题】

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:

【回答】

       表达式解析和计算是个很麻烦的事,问题中的运算还算简单,可以硬写出来,如果再带有括号什么的,就太难写了。

       这个问题可以用动态代码来解决,即让字符串变成可执行的代码,比如让“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 脚本

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值