/* Copyright @ 2004, The Institute for Genomic Research (TIGR). All rights reserved. */ /*************************************************************************** * Author: Jianwei(Jerry) Li. * Name: MathExpression (Version 1.0) * Date: Created: 10/12/2004 and modified: 11/04/2004 * Descp: A Java class that evaluate a formula passed in. ***************************************************************************/ package org.tigr.util.formula; import java.io.StringReader; import java.util.*; import org.tigr.util.formula.node.EvaluateException; public class MathExpression { private boolean gTreeReady, gUninary, gInt; private ExpressionParser gParser; private String gExpr; public MathExpression(){ gTreeReady = false; gUninary = false; gInt = true; } public MathExpression(String formula) { this(); setExpression(formula); parseFormula(); } public void setExpression(String expr) throws ExpressionException{ if(expr == null) { throw new ExpressionException(this, "Invalid expression : " + expr); } gExpr = expr; } public void IntegerResult(boolean b) { gInt = b; } /*************************************************************************** * Description: * returns the formula expression. **************************************************************************/ public String getExpression() { return gExpr; } public String evaluate() throws EvaluateException { String result = null; if(getExpression() == null) { throw new EvaluateException("Invalid empty expression"); } if(gTreeReady){ result = gParser.evaluate(); } if(result == null) { throw new EvaluateException("No evaluation"); } return result; } /**************************************************************************** * Description: * evaluates the formula with passed variables. *

Parameter: *
vals -- the values. *

Return: the results in a string format. ***************************************************************************/ public String evaluate(String[] vals) throws EvaluateException { int indx; String result = null; if(gExpr == null) { throw new EvaluateException("Invalid empty expression"); } indx = isUninary(gExpr); if(indx >= 0){ return vals[indx]; } if(gTreeReady){ result = gParser.evaluate(vals, gInt); } if(result == null) { throw new EvaluateException("No evaluation"); } return result; } /**************************************************************************** * Description: * check if the formula a uninary one. *

Parameter: *
forumula -- the formula to be checked. *

Return: -1 if it is not; otherwise, a positive number. ***************************************************************************/ private int isUninary(String formula){ int num = -1; try{ num = Integer.parseInt(formula); } catch (NumberFormatException ne){ return (-1); } return num; } private void parseFormula(){ if(gExpr.equals("")){ gUninary = true; return; } gParser = new ExpressionParser(gExpr); int indx = isUninary(gExpr); if(indx >= 0){ gUninary = true; } else { gTreeReady = gParser.execute(); } } }