我使用堆栈在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);
}
}发布于 2016-09-20 05:36:27
正如评论中提到的,把
if(ch == ' ') continue; 直接后
char ch = input.charAt(i);这将解决空白的问题。
另一个问题是
Pstack.push(result);在每次时间执行,而不仅仅是在计算运算符的情况下。
所以这句话应该是“否则”一案中的最后一句。
您还必须纠正从堆栈中弹出参数的方式。
例如,如果您有后缀表达式12- (应该计算为-1),则2位于堆栈的顶部,1紧随其后。在当前的解决方案中,结果将是2-1,因为参数是以错误的顺序检索的。
所以
int o1 = Pstack.pop();
int o2 = Pstack.pop();应更正为
int o2 = Pstack.pop();
int o1 = Pstack.pop();https://stackoverflow.com/questions/39584671
复制相似问题