我需要使用链表堆栈来评估后缀表达式。我想我需要一些算法帮助。我写 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());
}
}
答案 0 :(得分:1)
首先这个
if(Character.isDigit(expression.charAt(x))) {
digit = expression.charAt(x);
}
将位置x处的char的十进制ASCII值保存为double,对于char '1'
49
保存'3'
,51
为100
因此,你得到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代码)。你应该考虑到这个事实来折射你的程序。
此外:有原因,为什么你: