java 字符串转运算符

 1 import javax.script.ScriptEngine;
 2 import javax.script.ScriptEngineManager;
 3 import javax.script.ScriptException;
 4 
 5 /**
 6         *  有1个字符串(包含若干个加减乘除运算列),格式如下:2*3/7-1*6+4=;1.5+1/4*3.243-5*6=;2.32+30/4-64*1=;......" * ,请编写代码计算结果(保留2位小数)
 7         *  预期输出:
 8         *  2*3/7-1*6+4=?
 9         *  1.5+1/4*3.243-5*6==?
10         *  2.32+30/4-64*1=-?
11         */
12 class test {
13     public String calculate(String arg) throws ScriptException {
14         String result = "";
15         //TODO
16         //按照分号分割
17         String  temp[] = arg.split(";");
18         //以下方法实现 eval功能
19         ScriptEngineManager manager = new ScriptEngineManager();
20         ScriptEngine se = manager.getEngineByName("js");
21         for(String s:temp){
22             //去掉等于号
23             String sNew = s.substring(0,s.length()-1);
24             //保留二位小数
25             String sNewTwo =   String.format("%.2f", (Double) se.eval(sNew)).toString();
26             result = result + s+ sNewTwo + "\n";
27         }
28         result = result.substring(0,result.length()-2);
29         return result;
30     }
31 
32 
33 
34     public static void main(String [] args) throws ScriptException{
35         test testNew = new test();
36         String s = "2*3/7-1*6+4=;1.5+1/4*3.243-5*6=;2.32+30/4-64*1=;";
37         String sNew = testNew.calculate(s);
38         System.out.println(sNew);
39 
40     }
41 }

 

posted @ 2021-04-10 22:20  菜小鱼~  阅读(1597)  评论(0编辑  收藏  举报