2014-11-05 73 views
1

我需要使用链接列表堆栈评估postfix表达式。我想我需要一些关于算法的帮助。我写13+作为输入,但我得到100作为输出。使用堆栈评估Posfix(LinkedList)

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

嗯,首先,你要将字符放入声明为“Double”的MyStack中。这将强制从'char'转换为'double'并打印你的角色的数字值 – nem035 2014-11-05 16:37:48

回答

1

首先这个

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

在位置节省炭的十进制ASCII值x作为双,用于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); 
} 

然后将工作13+,并给予4作为结果。

这些线可以被移除:

character = expression.charAt(x); 
if(expression.charAt(x) == digit) 
{ 
    stack.push(digit); 
} 
1

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

另外:有没有理由,你为什么:

  • 使用自书面协议栈,而不是java.util.Stack中?
  • 使堆栈成为双倍而不是整数的容器?
+0

哦,这实际上是一项家庭作业,我们的老师希望我们使用自己写的作业。我认为在分割时我可以使用一些小数值,所以我使用它。谢谢你的帮助:) – Noxob 2014-11-06 00:05:53

+0

你应该小心这些改变(关于'Double'),因为'integer'-division是明确定义的。你的porgram不再符合这些定义。 – Turing85 2014-11-06 00:09:36

+0

ohh再次感谢你:) – Noxob 2014-11-06 00:54:38