Write postfix solution in Java -
i'm writing postfix solution. can't tell why doesn't work , keep getting -1 on output. can please help? i'll include runner , runner , actual postfix class.
import java.util.stack; import java.util.scanner; import static java.lang.system.*; public class postfixrunner { public static void main ( string[] args ) { postfix test = new postfix("2 7 + 1 2 + +"); system.out.println(test.solve()); test.setexpression("1 2 3 4 + + +"); system.out.println(test.solve()); test.setexpression("9 3 * 8 / 4 +"); system.out.println(test.solve()); test.setexpression("3 3 + 7 * 9 2 / +"); system.out.println(test.solve()); test.setexpression("9 3 / 2 * 7 9 * + 4 -"); system.out.println(test.solve()); test.setexpression("5 5 + 2 * 4 / 9 +"); system.out.println(test.solve()); } } and this...
import java.util.stack; import java.util.scanner; import static java.lang.system.*; public class postfix { private stack<integer> stack; private string theexp; public postfix() { } public postfix(string exp) { theexp = exp; stack = new stack<integer>(); } public void setexpression(string exp) { theexp= exp; while (!stack.isempty()){ stack.pop(); } } public int calc(int two, int one, char current) { int output; switch(current){ case '*': output=one*two; break; case '/': output=one/two; break; case '+': output=one+two; break; case '-': output=one-two; break; default: output=0; } return output; } public int solve() { (int i=0; i<theexp.length(); i++){ char current = theexp.charat(i); int currentint = (int)character.digit(current, 10); if (current!='*'||current!='/'||current!='+'||current!='-') stack.push(currentint); else stack.push(calc(stack.pop(), stack.pop(), current)); } return stack.pop(); } public string tostring(){ return stack.tostring(); } }
Comments
Post a Comment