infix to postfix program not working [duplicate]

2019-08-02 09:09发布

This question already has an answer here:

I am supposed to write a program to convert infix to postfix. It works for some, but other times not correctly. Especially on infix expressions containing parantheses. Could anyone give me a clue why this is wrong? For example, the infix expression

( ( 5 + 5 * ( 6 - 2 ) + 4 ^ 2 ) * 8 )

returns 5562-*42^++8*((2.

import java.io.*;
import java.util.Scanner;

public class InfixToPostfix
{
  //class attributes
  private  char curValue;
  private String postfix;
  private LineWriter lw;
  private ObjectStack os;

  //constructor
  public InfixToPostfix(LineWriter l, ObjectStack o)
  {
    curValue = ' ';
    lw=l;
    os=o;
  }

  public String conversion(String buf)
  {
    String temp =" ";
    StringBuffer postfixStrBuf= new StringBuffer(temp);
    char popped= new Character(' ');
    char topped=' ';

    for (int i=0; i<buf.length(); i++)
    {
      curValue= buf.charAt(i);

      if  (curValue == '(')
        os.push(curValue);

      if (curValue == ')')
      {
        while (popped != '(')
        {
          popped = ((Character)os.pop());
          if (popped != '(')
            postfixStrBuf.append(popped);
        }
      }

      if (isOperator(curValue))
      {
        if( os.isEmpty())
          os.push((Character)(curValue));
        else
          topped=((Character)os.top());

        if ( (priority(topped)) >= (priority(curValue)) && (topped != ' ') )
        {
          popped = ((Character)os.pop());
          if (popped != '(')
            postfixStrBuf.append(popped);
          //if it is a left paranthess, we want to go ahead and push it anyways
          os.push((Character)(curValue));
        }

        if ( (priority(topped)) < (priority(curValue)) && (topped != ' ') )
          os.push((Character)(curValue));
      }

      else if (!isOperator(curValue) && (curValue != ' ') && (curValue != '(' )  &&   (curValue != ')' ))
        postfixStrBuf.append(curValue);
    }

    //before you grab the next line of the file , pop off whatever is remaining off the stack and append it to
    //the infix expression

    getRemainingOp(postfixStrBuf);

    return postfix;

    //postfixStrBuf.delete(0, postfixStrBuf.length());
  }

  public int priority(char curValue)
  {
    switch (curValue)
    {
      case '^': return 3;
      case '*':
      case '/': return 2;
      case '+':
      case '-': return 1;
      default : return 0;
    }
  }

  public boolean isOperator(char curValue)
  {
    boolean operator = false;
    if ( (curValue == '^' ) || (curValue == '*') || (curValue == '/') || (curValue == '+' ) || (curValue == '-') )
      operator = true;
    return operator;
  }

  public String getRemainingOp(StringBuffer postfixStrBuf)
  {
    char popped=' ';
    while ( !(os.isEmpty()) )
    {
      opped = ((Character)os.pop());
      postfixStrBuf.append(popped);
    }
    postfix=postfixStrBuf.toString();
    return postfix;
  }
}

1条回答
我命由我不由天
2楼-- · 2019-08-02 09:46

I will only post how the inner loop should look like (without the castings everywhere):

if (curValue == '(') {
    os.push(curValue);
} else if (curValue == ')') {
    if(!os.isEmpty()) {
        topped = os.pop();
        while (!os.isEmpty() && (topped != '(')) {
            postfixStrBuf.append(topped);
            topped = os.pop();
        }
    }
} else if (isOperator(curValue)) {
    if (os.isEmpty()) {
        os.push(curValue);
    } else {
        while(!os.isEmpty() && (priority(os.top()) >= priority(curValue))) {
            popped = os.pop();
            postfixStrBuf.append(popped);
        }
        os.push(curValue);
    }
} else if (curValue != ' ') {
    postfixStrBuf.append(curValue);
}

Disclosure: it is pretty late already so I hope it is fine. You should fix the way variables are initialized and return of the getRemainingOp method.

查看更多
登录 后发表回答