java - How to evaluate a sign in a postfix expression? -
i have completed code postfix expression calculator, i'm unsure how go evaluating expression when come across negative sign.
for example, expression: -1-2-3 comes out in program:
original = -1-2-3
infix tokens = [[-;sign], [1;num], [-;op], [2;num], [-;op], [3;num]]
postfix = [[1;num], [-;sign], [2;num], [-;op], [3;num], [-;op]]
postfix evaluation = -2
obviously answer should -6, can't see logic behind making sign before number apply entire expression. i'm confident postfix method correct , know need create case when see sign, don't know after that.
here code far:
public static string eval(arraylist<tokenize.token> list) { stack<integer> stack = new stack<integer>(); (int i=0; i<list.size(); i++) { tokenize.token t = list.get(i); tokentype type = t.gettype(); if (type==tokentype.num) { string x = t.getvalue(); int x1 = integer.parseint(x); stack.push(x1); } else if (type==tokentype.op) { int y = stack.pop(); int x = stack.pop(); if(t.getvalue().equals("*")) { int z = y * x; stack.push(z); } else if(t.getvalue().equals("/")) { int z = y / x; stack.push(z); } else if(t.getvalue().equals("+")) { int z = y + x; stack.push(z); } else if(t.getvalue().equals("-")) { int z = y - x; stack.push(z); } } else if(type == tokentype.sign) { //???? } } return stack.pop() + ""; }
provided you've tokenized & distinguished sign (unary) minus (binary operator), , in postfix value pushed on stack -- appears case --
it's trivial:
else if (type == tokentype.sign) { int x = stack.pop(); x = -x; stack.push( x); } you pop number literal off, negate it, , push result on stack. unary operator ==> 1 input off stack, 1 output on.
Comments
Post a Comment