我需要使用链表堆栈来计算后缀表达式。我想我需要一些关于算法的帮助。我写 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());
}
}
最佳答案
首先这个
if(Character.isDigit(expression.charAt(x))) {
digit = expression.charAt(x);
}
保存小数ASCII位置 x 处的字符值为 double,对于字符 '1'
为 49
,对于 '3'
为 51
,因此您得到 100
结果
应该是
digit = Double.parseDouble("" + expression.charAt(x));
即解析 char 以获得它代表的 double 值。
这是一个小变化
character = expression.charAt(x);
if(Character.isDigit(character)) {
digit = Double.parseDouble("" + character);
stack.push(digit);
}
那么它将适用于 13+
并给出 4
作为结果。
这些行可以删除:
character = expression.charAt(x);
if(expression.charAt(x) == digit)
{
stack.push(digit);
}
关于java - 使用堆栈(链表)评估 Postfix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26762058/