【问题标题】:Prefix notation - Java前缀表示法 - Java
【发布时间】:2015-04-16 00:40:51
【问题描述】:
while (strToken.hasMoreTokens())
{
   String i = strToken.nextToken();              
   char ch = ' ';
   ch = i.charAt(0);
   int operand;
   int operator;

   if(Character.isDigit(ch))
   {
       operand = Integer.parseInt(i);
       operandStack.push(operand);
   }
   else
   {
       operator = i.charAt(0);
       operatorStack.push(operator);
   }
}

while(operandStack.size() > 1)
{
   operandStack.push(operate(operandStack.pop(),
   operandStack.pop(), operatorStack.pop()));
}

resultTextField.setText(Integer.toString(operandStack.peek()));

我的代码不会以前缀表示法计算操作数。我应该如何修改它以评估前缀表示法的操作数。

【问题讨论】:

  • 'code does not evaluate' 不是问题描述。相反会发生什么?用什么输入?什么输出?预期和实际?当你already had working code时你怎么会发这个?
  • @EJP 输入:* + 16 4 + 3 1:预期输出:80,实际输出:128
  • 请使用此信息更新您的问题,这样人们就不必阅读所有的 cmets 来了解全局。
  • 单元测试在这里为您提供帮助。

标签: java prefix notation


【解决方案1】:

您填充堆栈然后开始计算,而不是在扫描期间遇到运算符时,您应该弹出操作数,计算结果(通过将遇到的运算符应用于操作数)并将结果压入堆栈。从右向左扫描。如果您从左到右扫描,算法是不同的。您可以在波兰表示法的维基百科页面上阅读这两种实现。

你现在在做什么:

input: * + 16 4 + 3 1
operand stack: 16 4 3 1
operator stack: * + + 
pop + pop 3 pop 1 push 4
operand stack: 16 4 4 
operator stack: * +
pop + pop 4 pop 4 push 8
operand stack: 16 8
operator stack: *
pop * pop 8 pop 16 
result = 16 * 128

你需要做什么(从右到左):

input: * + 16 4 + 3 1
push 1 push 3
operand stack: 1 3 
operator: +    (no need for the operator stack)
pop 1 pop 3 push 3+1 = 4
operand stack: 4
push 4 push 16 
operand stack: 4 4 16
operator + 
pop 16 pop 4 push 4+16 = 20
operand stack: 4 20
operator *
pop 20 pop 4 result 4*20 = 80

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多