前缀表达式评估错误 - Java

时间:2015-04-13 00:52:19

标签: java expression prefix

private class InputListener implements ActionListener
    {
      public void actionPerformed(ActionEvent e)
      {
         // Create an integer and character stack
         Stack<Integer> operandStack = new Stack<Integer>();
         Stack<Character> operatorStack = new Stack<Character>();

         // User input in input text field
         String input = inputTextField.getText();

         // Create string tokenizer containing string input
         StringTokenizer strToken = new StringTokenizer(input);

         // Loop while there are tokens
         while (strToken.hasMoreTokens())
         {
             String i = strToken.nextToken();
             int operand;
             char operator;

             try
             {
                 operand = Integer.parseInt(i);
                 operandStack.push(operand);
             }
             catch (NumberFormatException nfe)
             {
                 operator = i.charAt(0);
                 operatorStack.push(operator);
             }
          }

          // Loop until there is only one item left in the
          // operandStack. This one item left is the result
          while(operandStack.size() > 1)
          {
            // Perform the operations on the stack
            // and push the result back onto the operandStack
            operandStack.push(operate(operandStack.pop(),
            operandStack.pop(), operatorStack.pop()));
          }

          // Display the result as a string in the result text field
          resultTextField.setText(Integer.toString(operandStack.peek()));
       }
       // Sum and product computed
       public int operate(Integer operand1, Integer operand2, char operator)
       {
         switch(operator)
         {
            case '*':
               return operand2 * operand1;
            case '/':
               return operand2 / operand1;
            case '%':
               return operand2 % operand1;
            case '+':
               return operand2 + operand1;
            case '-':
               return operand2 - operand1;
            default:
               throw new IllegalStateException("Unknown operator " + operator + " ");
          }
        }
     }

提供的前缀表达式代码错误地评估具有多个运算符的表达式。表达式* + 16 4 + 3 1应该评估为80 = ((16 + 4) * (3 + 1)),而是评估为128,我认为评估为:((16 + 4) * (3 + 1) + (16 * 3))。如何编辑代码以更正此问题?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

在前缀评估中,要记住的重要事项是

操作数1 = pop();

操作数2 = pop();

并说运营商是 -

推送的值是操作数1 - 操作数2而不是操作数2 - 操作数1

但是其他因素导致* + 16 4 + 3 1评估为128。

我在java中使用以下算法进行评估,并且工作正常

1.将前缀表达式作为字符串放在变量中,字符用单个空格分隔。

2.将字符串从索引长度-1转换为0

3.如果是一个数字,执行推送,如果它是一个多位数,首先获取完整数字,然后推送它

4.如果它是一名操作员,那么就完成我在答案开头提到的事情。

这是一个简单的代码。

import java.io.*;
import java.util.*;
class PREFIXEVAL
{
public static void main(String []args)throws IOException
{
 String p,n="";StringBuffer b;int i,op1,op2;char c;Stack<Integer> s=new Stack<Integer>();
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 System.out.println("enter the prefix expression separated by spaces");
 p=br.readLine();
 i=p.length()-1;
 while(i>=0)
 {
     c=p.charAt(i);
     if(c>=48&&c<=57)
     n=n+c;
     else if(c==' '&&!n.equals(""))
     {/*handles both single and multidigit numbers*/
         b=new StringBuffer(n);b.reverse();n=b.toString();
         s.push(Integer.parseInt(n));n="";
        }
        else 
        {
            if(c=='+')
            {
                op1=s.pop();
                op2=s.pop();
                s.push(op1+op2);
            }
            else if(c=='-')
            {
                op1=s.pop();
                op2=s.pop();
                s.push(op1-op2);
            }
            else if(c=='*')
            {
                op1=s.pop();
                op2=s.pop();
                s.push(op1*op2);
            }
            else if(c=='%')
            {
                op1=s.pop();
                op2=s.pop();
                s.push(op1%op2);
            }
            else if(c=='/')
            {
                op1=s.pop();
                op2=s.pop();
                s.push(op1/op2);
            }
        }
        i--;
    }
    System.out.println("the prefix expression evaluates to "+s.peek());
  }
 }