简体   繁体   中英

Prefix notation - Java

while (strToken.hasMoreTokens())
{
   String i = strToken.nextToken();              
   char ch = ' ';
   ch = i.charAt(0);
   int operand;
   int operator;

   if(Character.isDigit(ch))
   {
       operand = Integer.parseInt(i);
       operandStack.push(operand);
   }
   else
   {
       operator = i.charAt(0);
       operatorStack.push(operator);
   }
}

while(operandStack.size() > 1)
{
   operandStack.push(operate(operandStack.pop(),
   operandStack.pop(), operatorStack.pop()));
}

resultTextField.setText(Integer.toString(operandStack.peek()));

My code does not evaluate operands in prefix notation. How should I revise it to evaluate operands in prefix notation.

You fill your stack and then start to evaluate, instead when encountering operator during the scan you should pop the operands, compute the result ( by applying encountered operator to the operands) and push the result onto the stack. Scan from right to left. If you are scanning left to right the algorithm is different. You can read about both implementations on Polish notation's wikipedia page.

What you are doing now:

input: * + 16 4 + 3 1
operand stack: 16 4 3 1
operator stack: * + + 
pop + pop 3 pop 1 push 4
operand stack: 16 4 4 
operator stack: * +
pop + pop 4 pop 4 push 8
operand stack: 16 8
operator stack: *
pop * pop 8 pop 16 
result = 16 * 128

What you need to do (right to left):

input: * + 16 4 + 3 1
push 1 push 3
operand stack: 1 3 
operator: +    (you don't need operator stack)
pop 1 pop 3 push 3+1 = 4
operand stack: 4
push 4 push 16 
operand stack: 4 4 16
operator + 
pop 16 pop 4 push 4+16 = 20
operand stack: 4 20
operator *
pop 20 pop 4 result 4*20 = 80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM