缀为Postfix,我的程序已编译,但不会产生输出 java

问题描述

所以我必须使用示例a b /(c-a)+ d e将中缀转换为后缀。我的代码显示了一些警告,没有显示任何错误,它已编译但没有输出。当我运行时,它将向我显示以下消息。

Exception in thread "main" java.lang.NullPointerException
    at LinkedStackTest$Convert.convertToPostfix(LinkedStackTest.java:40)
    at LinkedStackTest$Convert.main(LinkedStackTest.java:60)

我尝试多次查看代码,但仍然不知道自己做错了什么。任何帮助或建议都将非常感谢!

我的代码

public class LinkedStackTest
{
    static class Convert
    {
        static int getPriority(char ch)
        {
            switch (ch)
            {
                case '+':
                case '-':
                    return 1;
                case '*':
                case '/':
                    return 2;
            }
            return -1;
        }

        public static String convertToPostfix(String infix)
        {
            LinkedStack<Character> linkStack = new LinkedStack<>();
            String postfix = "";

            for (int i = 0; i < infix.length(); i++)
            {
                char ch = infix.charat(i);

                if (Character.isLetterOrDigit(ch)) {
                    postfix += ch;
                } else if (ch == '(') {
                    linkStack.push(ch);
                } else if (ch == ')') {
                    while (linkStack.peek() != '(') {
                        postfix += linkStack.peek();
                        linkStack.pop();
                    }
                } else {
                    while (!linkStack.isEmpty() && getPriority(ch) <= getPriority(linkStack.peek())) {
                        if (linkStack.peek() == '(')
                            return "Invalid";
                        postfix += linkStack.peek();
                    }
                    linkStack.push(ch);
                }
            }
            while (!linkStack.isEmpty())
            {
                if(linkStack.peek() == '(')
                    return "Invalid Expression";
                postfix += linkStack.pop();
            }
            return postfix;
        }

        public static void main(String[] args) throws Exception
        {
            String infix = "a*b/(c-a)+d*e";
            String postfix = convertToPostfix(infix);
            System.out.println("Infix: " + infix);
            System.out.println("Postfix: " + postfix);
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)