1

我正在使用堆栈在 java 中创建一个后缀计算器。我已经写好了主要部分,但是我遇到了一些问题。对于初学者,我必须考虑空格,我不确定如何使用我当前的设置来做到这一点。我不确定这是否会完全修复程序,但这将是一个开始。任何帮助将不胜感激。

 import java.util.Scanner;
 import java.util.Stack;
 public class Postfix 
{
public static void main(String[]args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a Postfix expression");
    String input = sc.nextLine();
    Stack<Integer> Pstack = new Stack<Integer>();
    int result = 0;
    for(int i=0; i<input.length();i++)
    {
        char ch = input.charAt(i);

        if(ch>='0' && ch<='9')
        {
            Pstack.push((int)(ch-'0'));
        }
        else
        {
            int o1 = Pstack.pop();
            int o2 = Pstack.pop();

            switch(ch)
            {
            case '+':result=o1+o2;
            break;
            case '-':result=o1-o2;
            break;
            case '/':result=o1/o2;
            break;
            case '*':result=o1*o2;
            }
        }
        Pstack.push(result);
    }
    result = Pstack.pop();
    System.out.println("result: "+ result);
   }
}
4

1 回答 1

2

As mentioned in the comments, put

if(ch == ' ') continue; 

directly after

char ch = input.charAt(i);

This will fix the issue with the whitespace.

Another issue is that

Pstack.push(result);

is executed every time, not just in case an operator has been evaluated.

So this statement should be the last one within the "else" case.

You also have to correct the way how the arguments are popped from the stack.

e.g. if you have the postfix expression 12- (which should evaluate to -1), 2 is on top of the stack and 1 comes after. In the current solution the result would be 2 -1 as the arguments are retrieved in the wrong order.

So

int o1 = Pstack.pop();
int o2 = Pstack.pop();

should be corrected to

int o2 = Pstack.pop();
int o1 = Pstack.pop();
于 2016-09-20T05:36:27.133 回答