使用堆栈(链接列表)评估Postfix

时间:2014-11-05 16:22:37

标签: java collections stack postfix-notation

我需要使用链表堆栈来评估后缀表达式。我想我需要一些算法帮助。我写 13+ 作为输入,但我得到100作为输出。

PostfixCalculator类:

public class PostfixCalculator{
    String expression;
    MyStack stack = new MyStack<Double>();

    public PostfixCalculator(String postFixExpression)
    {
         expression = postFixExpression;
    }

    public String calculate()
    {
        String output = "";
        char character = ' ';
        double digit = 0;

        for(int x = 0; x < expression.length(); x++)
        {
            if(Character.isDigit(expression.charAt(x))) {
                    digit = expression.charAt(x);
            }
            character = expression.charAt(x);
            if(expression.charAt(x) == digit)
            {
                stack.push(digit);
            }
            else if(character == '*')
            {
                double tmp = (double) stack.pop() * (double) stack.pop();
                stack.push(tmp);
            }
            else if(character == '/')
            {
                double tmp = (double) stack.pop() / (double) stack.pop();
                stack.push(tmp);
            }
            else if(character == '+')
            {
                double tmp = (double) stack.pop() + (double) stack.pop();
                stack.push(tmp);
            }
            else if(character == '-')
            {
                double tmp = (double) stack.pop() - (double) stack.pop();
                stack.push(tmp);
            }
        }

        while(!stack.isEmpty())
        {
            output = output + (double) stack.pop();
        }

        return output;
    }
}

PostfixCalculatorTest类:

import java.util.Scanner;

public class PostfixCalculatorTest
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Type the postfix expression that you want to evaluate");
        String expression = input.next();
        PostfixCalculator calculator = new PostfixCalculator(expression);
        System.out.println(calculator.calculate());
    }
}

2 个答案:

答案 0 :(得分:1)

首先这个

if(Character.isDigit(expression.charAt(x))) {
     digit = expression.charAt(x);
}

将位置x处的char的十进制ASCII值保存为double,对于char '1' 49保存'3'51100因此,你得到digit = Double.parseDouble("" + expression.charAt(x)); 作为结果

应该是

character = expression.charAt(x);
if(Character.isDigit(character)) {
    digit = Double.parseDouble("" + character);
    stack.push(digit);
}

即。解析char以获取它所代表的double值。

这是小改变

13+

然后它适用于4并提供character = expression.charAt(x); if(expression.charAt(x) == digit) { stack.push(digit); } 作为结果。

可以删除这些行:

{{1}}

答案 1 :(得分:1)

问题是自动类型转换。 Java能够将char转换为double。你得到的是char'1'(49)的ASCII码和char'3'(51)的ASCII码。所以你的程序在理论上做的是正确的,除了你必须从你读入的实际ASCII代码中减去48(作为0的ASCII代码)。你应该考虑到这个事实来折射你的程序。

此外:有原因,为什么你:

  • 使用自编写的Stack而不是java.util.Stack?
  • 使堆栈成为Double而不是Integer的容器?
相关问题