开发者

Getting wrong outputs in infix to postfix application with java

开发者 https://www.devze.com 2023-01-26 19:07 出处:网络
i recently wrote a java program that takes an infix expression and converts it into a postfix expression. It works for the most part but i am getting wrong outputs for some expressions. For example th

i recently wrote a java program that takes an infix expression and converts it into a postfix expression. It works for the most part but i am getting wrong outputs for some expressions. For example the expression a+b+c+d+e will output abcde+++++ when it should output a b + c + d + e +.

import java.util.Stack;
public class ITP {

    public static Stack<Character> stack;
    public static String inFixExp;
    public static String postFixExp = "";

    public static String infixToPostfix(String exp){
        ITP o = new ITP();
        stack = new Stack<Character>();
        inFixExp = exp;

        for (int i = 0; i < inFixExp.length(); i++) {

            if (inFixExp.charAt(i) == '(')
                stack.push(inFixExp.charAt(i));
            else if (inFixExp.charAt(i)==')'){
                while (stack.peek()!='('){
                    postFixExp += stack.pop();       
                }
                stack.pop();
            }else if ((inFixExp.charAt(i)=='*')||(inFixExp.charAt(i)=='/')||(inFixExp.charAt(i)=='+')||(inFixExp.charAt(i)=='-')){
                while(!stack.isEmpty() && o.getPredence(inFixExp.charAt(i)) < o.getPredence(stack.peek()))
                    postFixExp += stack.pop();
                stack.push(inFixExp.charAt(i));
            }else
                postFixExp += inFixExp.charAt(i);

        }
        while(!stack.isEmpty())
                postFixExp += stack.pop();



        return postFixExp;
    }

    public int getPredence(Object op) {

        if((op.equals("*")) || (开发者_开发百科op.equals("/")))
            return 3;
        else if((op.equals("+"))||(op.equals("-")))
            return 1;
        else
            return 0;
    }

}

I found out that if i change the < with <= in line 24 it will fix this problem but then i will get an empty stack error and some other expressions will output incorrectly, such as a+b*c which will output ab+c*, when it is supposed to be abc*+.


Your

if ((inFixExp.charAt(i) == '*') || ...

checks charAt() but your getPredence(precedence?) checks for a String, try comparing against a char instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消