import java.util.regex.*;
import java.util.*;
import java.text.*;
public class JEvaluator {
private String expression ;
private Map variables;
private Stack tokens;
/**
* @param expression
*/
public JEvaluator(String expression){
this.expression = expression.toUpperCase();
variables=new HashMap();
}
public static void main(String[] args)
{
JEvaluator r = new JEvaluator("x<=10/z and y=8*z and name<>'CESAR' or birth_date try{
r.setVariable("x",5);
r.setVariable("y",50);
r.setVariable("z",8);
r.setVariable("name","CESAR");
r.setVariable("birth_date",new Date());
//r.printStack();
System.out.println("result = " + r.eval());
r.setExpression("10+3*2^x-10*sin(1-x/y)");
r.setVariable("x",5.36);
r.setVariable("y",47);
System.out.println("result = " + r.eval());
r.setExpression("10+sin(3^(1/2))");
System.out.println("result = " + r.eval());
}catch(Exception ex){
ex.printStackTrace();
r.printStack();
}
}
/**
* @param s, the expression to be evaluated
*/
public void setExpression(String s){
this.expression = s.toUpperCase(); //case insensitive.
this.tokens=null;
this.variables=new HashMap();
}
/**
* @return the current expression
*/
public String getExpression(){
return this.expression;
}
/**
* @return String[] array of current variable names
*/
public String[] getVariables(){
String[] vars=new String[variables.size()];
variables.keySet().toArray(vars);
return vars;
}
/**
* Sets the value of the variables present in the expression.
* @param var, variable name (case insentive)
* @param val, value
*/
public void setVariable(String var, Object val){
//if(!variables.containsKey(var)) throw Exception("No existe variable " + var);
variables.put(var.toUpperCase(),val);
}
/**
* Evaluates the current expression, and returns the result Object: double or boolean
* @return result (double for mathematical expression, and boolean for logical expression)
* @throws Exception
*/
public Object
计算器基础原理代码(java)
最新推荐文章于 2021-03-10 22:49:02 发布
这个博客展示了如何使用Java编写一个简单的表达式求值器,包括处理变量、运算符和逻辑表达式。代码中实现了括号、算术运算、比较操作、逻辑运算以及对变量的赋值等功能。
摘要由CSDN通过智能技术生成