现在的位置: 首页 > 综合 > 正文

表达式计算//java类

2013年01月18日 ⁄ 综合 ⁄ 共 818字 ⁄ 字号 评论关闭

昨天,看到一求助表达式计算的帖子,才知道,原来java里有封装了这样的类。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class expression {
    public static void main(String []args) throws IOException, ScriptException
    {
        String str=new String();
        BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
        while(true==true)
        {
            System.out.println("请输入要计算的表达式:");
            str=in.readLine();
            if(str.equals("end"))
                break;
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            Object result = engine.eval(str);
        
        System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
        }
    }
}

抱歉!评论已关闭.