Инфикс для постфикса с использованием двух стеков

Мне нужна помощь с моим методом оценки. Вывод, который я получаю, совершенно неверен. МОЙ КОД ДЕЛАЕТ ЭТО: Вход: ( 5 + 3) * 3 Выход: Стек операнда: [ (, 5, + 3 +,), * 4 * ] Стек оператора: [] ВЫХОД ДОЛЖЕН БЫТЬ: Стек операнда: [ 5 3 + 4 * ] Стек оператора: [] * Примечание: пробелы должны быть между числами

Вот мой метод оценки:

/**
  * Evaluates the specified postfix expression. If an operand is encountered,
  * it is pushed onto the operand stack. If an operator is encountered, two
  * operands are popped, the expression is evaluated, and the result is
  * pushed onto the operand stack.
  * 
  * @param expr string representation of a postfix expression
  * @return value of the given expression
  */
 public String evaluate(String expr) {

  // A variable to hold the resulting postfix expression.
  String result;
  // A string variable to hold the individual elements of user's input string.
  String token;
  // A parser to read the individual tokens of user input, tokens must be separated by whitespace.
  Scanner parser = new Scanner(expr);

  while (parser.hasNext()) {
   // Evaluating the expression one token at a time.
   token = parser.next();
   
   // 1) An operand is either the first or second operand for an operator.
   // If the operator stack is empty or if a left parenthesis is on top of the stack,
   // the operand is the first operand for an operator. Push the operand onto the operand stack.
   if (operatorStack.isEmpty() || operatorStack.peek().equals("(")) {
    // Operand 1 
    operand1 = token;
       
    // Pushing operand1 onto the operand stack
    operandStack.push(operand1);
   }

   // 1) Otherwise, the operand is the second operand for an operator. The first operand should be on top of
   // the operand stack, and the operator should be on top of the operator stack. Pop the
   // first operand and the operator from the stacks, and form the postfix expression
   // representing applying the operator to its two operands. This expression is an operand
   // to which another operator may be applied, so push it onto the operand stack.
  
   else {
    // Operand 2
    String operand2 = token;

    // Popping current operator and operand1
     operand1 = operandStack.pop();
     currentOperator = operatorStack.pop();

    // Forming the resulting expression
     resultingExpression = (operand1 + " " + operand2 + " " + currentOperator + " ");

    // Pushing the resulting expression onto the operandStack
    operandStack.push(resultingExpression);
    
   }
   
   // 2) A right parenthesis marks the end of an infix operand expression. The matching left
   // parenthesis should be on top of the operator stack, and the postfix operand expression
   // corresponding to the infix operand expression should be on top of the operand stack.
   // Pop the left parenthesis off the operator stack. If the stack is now empty or if the token 
   // on top of the stack is another left parenthesis, the operand on top of the operand stack
   // is the first operand for an operator, assuming the end of the whole infix expression has
   // not been reached. In this case, do nothing further.Otherwise, the postfix expression
   // on top of the operand stack is the second operand for an operator. 
   // The first operand should be immediately below it, and the operator should be on
   // top of the operator stack.Pop both operands and the operator from the stacks, and form
   // the postfix expression representing applying the operator to its operands. As in 1
   // above, push this expression onto the operand stack.
   
   if (isRightParen(token)) {
    // Popping left parenthesis
    operatorStack.pop();
    
    if (operatorStack.isEmpty() || operatorStack.peek().equals("(")) {
     // First operand for an operator
     operand1 = operandStack.peek();
    } 
    
    else {

     // Second operand for an operator
     operand2 = operandStack.peek();

     // Pop both operands
     operandStack.pop();
     operandStack.pop();

     // Pop operator
     currentOperator = operatorStack.pop();

     // Forming the resulting expression
     resultingExpression = (operand1 + " " + operand2 + " " + currentOperator + " ");

     // Pushing the resulting expression onto the operandStack
     operandStack.push(resultingExpression);
     }
   

    }
   
   // 3) To process an operator or a left parenthesis, simply push it onto the operator stack.
   
    // If token is an operator push it on the operator stack.
     if (isOperator(token)) {
      operatorStack.push(token); 
       }
    // If token is a left parenthesis push it on to the operator stack.
     else if (isLeftParen(token)) {
      operatorStack.push(token);
      }
   

   
   }
  
  // Returning the completed postfix result
  result = ("Operand Stack: " + operandStack.toString() + " " + "Operator Stack: " + operatorStack.toString());
  return result;
 }

1 ответ

Взглянув на ваш код, я могу дать вам следующие предложения, не давая реального ответа, потому что может показаться, что это какой-то классовый проект? Взгляните на алгоритм шунтирующего двора EWD и на обратную польскую запись (RPN). Обе эти статьи Википедии содержат псевдокод, который описывает, как реализовать алгоритм. Я надеюсь, что это помогает, и удачи!

Другие вопросы по тегам