使用 java 在中缀中获取错误的输出到后缀应用程序 [英] Getting wrong outputs in infix to postfix application with java

查看:49
本文介绍了使用 java 在中缀中获取错误的输出到后缀应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一个java程序,它接受一个中缀表达式并将它转换成一个后缀表达式.它在大多数情况下都有效,但我在某些表达式中得到了错误的输出.例如,表达式 a+b+c+d+e 将在应该输出时输出 abcde+++++a b + c + d + e +.

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;
    }

}

我发现如果我改变 <使用 <= 在第 24 行它会解决这个问题,但是我会得到一个空堆栈错误,并且其他一些表达式会输出不正确,例如 a+b*c 将输出 ab+c*,当它应该是abc*+.

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*+.

推荐答案

你的

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

检查 charAt() 但您的 getPredence(precedence?) 检查 String,尝试与 char 进行比较代码>代替.

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

这篇关于使用 java 在中缀中获取错误的输出到后缀应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆