int a,b,c,d;
a=10; b=2; c=3;
d=a-b*c;
System.out.println(d);
这种情况下d的值是正确的
如果a-b*c作为公式从数据库或文本文件中取出(假设是String类型)如何保持d的值正确呢?
java有没有办法实现,不用数据结构的办法和迂回向下的办法。
 

解决方案 »

  1.   

    int a=1;
        int b=2;
        String str="a*b";
        str=str.replaceAll("a",a+"");
        str=str.replaceAll("b",b+"");
        Interpreter i = new Interpreter();
        try {
          Object result = i.eval(str);
          System.out.println("Result is " + result.toString());
        }
        catch (EvalError e) {
          System.out.println("eval error");
        }
      

  2.   

    此类Interpreter要到下面的网站下载插件
    http://www.beanshell.org/download.html
      

  3.   

    int a=1;
        int b=2;
        String str="a*b";//公式
        str=str.replaceAll("a",a+"");//把公式里的变量替换成值
        str=str.replaceAll("b",b+"");//把公式里的变量替换成值
        Interpreter i = new Interpreter();//创建计算表达式字符串对象
        try {
          Object result = i.eval(str);//调用方法eval()计算字符串表达式,得到计算结果result
          System.out.println("Result is " + result.toString());//输出结果
        }
        catch (EvalError e) {
          System.out.println("eval error");//表达式有错
        }
      

  4.   

    谢谢lip009和各位是不是说java语言本身是无法解决这类问题,只有通过编写其他程序来解决,通过数据结构的办法和迂回向下的办法都可以解决,而且不是很难,没有必要下插件
      

  5.   

    数据结构用堆栈
    迂回向下是java编程艺术上的方法,网上有下载我想知道语言本身有没有这种功能来实现
      

  6.   

    语言本身好像是没有这种方法,就像javascript里的eval一样