Проблемы при конвертации Infix в Postfix с использованием стеков и очередей в Java - PullRequest
0 голосов
/ 20 марта 2019

Работает, если уравнение содержит какой-либо вариант NUM + / - / * // NUM. Однако добавление большего количества операторов приведет к тому, что оно не будет работать, а скобки вызовут бесконечный цикл. Я надеялся, что кто-нибудь скажет мне, где я ошибся Я прошу прощения за длину кода, любая помощь будет оценена.

/*
Converts String equation in an Infix form into a Postfix format.
postFix is a stack object that currently uses the default constructor of DSAStack
hence there is an upper limit to how many characters can be entered. 
Likewise for infix.
opStack contains the operators for as long as it is needed.

eqArray contains the entered equation in an Array. The original line will be split on " ", aka a space between "characters".

order ensures that precedence of operators are kept.
*/   
    private static DSAQueue parseInfix(String equation)
    {
        DSAQueue postfix = new DSAQueue();
        DSAStack opStack = new DSAStack();
        DSAQueue infix = new DSAQueue();

        String term = "1";
        String[] eqArray = readType.splitLine(equation, " ");

        for(int i = 0; i < eqArray.length; i++)
        {
            infix.enqueue(eqArray[i]);
        }       
        while(!infix.isEmpty())
        {
            term = null;
            term = (String) infix.dequeue();

            if(term.equals("("))
            {
                opStack.push("(");
            }
            else if(term.equals(")"))
            {
                while(!(opStack.peek().equals("(")))
                {
                    postfix.enqueue(opStack.pop());
                }
                opStack.pop();  
            }
            else if(term.equals("+") || term.equals("-") || term.equals("*") || term.equals("/")
            {
                while((!opStack.isEmpty())&&((opStack.peek()).equals("(")))
                { 
                    if(order(opStack.peek()) > order(term))
                    {
                        postfix.enqueue(opStack.pop());
                    }
                }
                opStack.push(term);
            }
            else
            {
                postfix.enqueue(term);
            }
        }

        while(!opStack.isEmpty())
        {
            postfix.enqueue(opStack.pop());
        }        

        return postfix;
    }
...