/** This class provides methods that are useful for * processing mathematical expressions as strings. * * @author Adam Blank */ public class EvaluatorUtilities { /** Returns true if the given string can be interpreted * as a number, false otherwise. */ public static boolean isNumber(String x) { for (int i = 0; i < x.length(); i++) { if (x.charAt(i) < '0' || x.charAt(i) > '9') { return false; } } return true; } /** Returns the index in the given string of the next operator to be * evaluated.
Returns -1 if there is no operator in exp.

* * For example, if exp is "(((1+2)*3)+(4*2))", nextOperator * would return 10, because the "+" is the outermost operator * and should be evaluated next.

* * This method considers "+", "*", "^", and "-" to be operators. */ public static int nextOperatorIndex(String exp) { int parens = 0; for (int i = 0; i < exp.length(); i++) { char c = exp.charAt(i); if (c == '(') { parens++; } else if (c == ')') { parens--; } if (parens == 0 && (c == '+' || c == '*' || c == '^' || c == '-')) { return i; } } return -1; } /** Returns a character representing the next operator in * the given string.
Returns '?' if there is no such operator.

* * See {@link #nextOperatorIndex(String) nextOperatorIndex} for more description of 'next' * and 'operator'. */ public static char nextOperator(String exp) { int opIndex = nextOperatorIndex(exp); if (opIndex == -1) { return '?'; } return exp.charAt(nextOperatorIndex(exp)); } } class NotImplementedException extends Exception { private static final long serialVersionUID = 1L; }