Solving simple string expressions (1+2*3) in Java [Almost Done] -
i'm trying solve simple string expressions e.g. 1+2*3/4, without brackets. i'm done simple integer part, above expression work perfectly, i'm stuck decimal values, example 1.1/2.2*4.4 want push whole decimal number stack (double), i'm working on quite time not quite getting it, appreciated. current code is:
import java.util.stack; import java.text.decimalformat; public class evaluatestring { public static double evaluate(string expression) { char[] tokens = expression.tochararray(); decimalformat df = new decimalformat("#.##"); // stack numbers: 'values' stack<double> values = new stack<double>(); // stack operators: 'ops' stack<character> ops = new stack<character>(); (int = 0; < tokens.length; i++) { // current token whitespace, skip if (tokens[i] == ' ') continue; // current token number, push stack numbers if (tokens[i] >= '0' && tokens[i] <= '9') { stringbuffer sbuf = new stringbuffer(); // there may more 1 digits in number while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') sbuf.append(tokens[i++]); values.push(double.parsedouble(sbuf.tostring())); } // current token operator. else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { // while top of 'ops' has same or greater precedence current // token, operator. apply operator on top of 'ops' // top 2 elements in values stack while (!ops.empty() && hasprecedence(tokens[i], ops.peek())) values.push(applyop(ops.pop(), values.pop(), values.pop())); // push current token 'ops'. ops.push(tokens[i]); } } // entire expression has been parsed @ point, apply remaining // ops remaining values while (!ops.empty()) values.push(applyop(ops.pop(), values.pop(), values.pop())); // top of 'values' contains result, return return double.parsedouble(df.format(double.parsedouble(string.valueof(values.pop())))); } // returns true if 'op2' has higher or same precedence 'op1', // otherwise returns false. public static boolean hasprecedence(char op1, char op2) { if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; else return true; } // utility method apply operator 'op' on operands 'a' // , 'b'. return result. public static double applyop(char op, double b, double a) { switch (op) { case '+': return + b; case '-': return - b; case '*': return * b; case '/': if (b == 0) throw new unsupportedoperationexception("cannot divide zero"); return / b; } return 0; } }
there going change in part values getting pushed in 'value' stack.
you have done ! more little change:
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
needs replaced
while (i < tokens.length && (character.isdigit(tokens[i]) || tokens[i] == '.'))
Comments
Post a Comment