简体   繁体   English

前缀表达式评估不正确-Java

[英]Prefix Expression evaluating incorrectly - Java

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 + " ");
          }
        }
     }

The prefix expression code provided is incorrectly evaluating expressions with more than one operator. 提供的前缀表达式代码使用多个运算符错误地评估了表达式。 The expression: * + 16 4 + 3 1 should evaluate to 80 = ((16 + 4) * (3 + 1)) , but instead it evaluates to 128 , which I think is evaluating as: ((16 + 4) * (3 + 1) + (16 * 3)) . 表达式: * + 16 4 + 3 1应该计算为80 = ((16 + 4) * (3 + 1)) ,但是它的计算结果为128 ,我认为计算结果为: ((16 + 4) * (3 + 1) + (16 * 3)) How do I edit the code to correct this problem? 如何编辑代码以更正此问题? Thank you for your help. 谢谢您的帮助。

In prefix evaluation,Important thing to remember is 在前缀评估中,要记住的重要事项是

operand 1= pop(); 操作数1 = pop();

operand 2= pop(); 操作数2 = pop();

and say the operator is - 说经营者是-

The value that is pushed is operand 1 - operand 2 and not operand 2 - operand 1 推入的值是操作数1-操作数2而不是操作数2-操作数1

But something else is causing * + 16 4 + 3 1 to evaluate to 128. 但是其他原因导致* + 16 4 + 3 1的计算结果为128。

I used the following algo for evaluating in java and it works fine 我使用以下算法在Java中进行评估,效果很好

1.Take the prefix expression as a string in a variable with characters separated by single space. 1.将前缀表达式作为字符串包含在变量中,字符之间用单个空格分隔。

2.Traverse the string from index length-1 to 0 2.将字符串从索引长度1遍历到0

3.If its a number, perform push ,and if its a multidigit number,first obtain the full number and then push it 3.如果是数字,则执行压入;如果是数字,则先获取完整的数字,然后再压入

4.If its an operator then simply do the thing which i mentioned in beginning of the answer. 4.如果是操作员,则只需做我在答案开头提到的事情即可。

It is a simple code. 这是一个简单的代码。

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());
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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