4

这个 EmptyStackException 继续弹出。不知不觉中,我的堆栈中没有任何内容,而是用户输入的第一个元素。但是,我不确定代码的缺陷在哪里。(很多地方)但我只需要修复这个错误。

import java.util.*;

public class stacks2 {

public static void main (String []args){
System.out.printf("Enter a math equation in reverse polish notation:\n");

//Create stack of Strings
Stack<String> rpnStack = new Stack<String>();
//Create Scanner 
Scanner input = new Scanner(System.in);
//String in = input.next();

while(input != null) {
    String in = input.next();
        // Tokenize string based on spaces.
        StringTokenizer st = new StringTokenizer(in, " ", true);
            while (st.hasMoreTokens()) {
             rpnStack.push(st.nextToken());
         }
    //Send stack to Calculation Method
    calculate(rpnStack);
     }
}

public static void calculate(Stack<String> stack) {
    // Base case: stack is empty => Error, or finished
    if (!stack.isEmpty())
      // throw new StackUnderflowException("Empty Stack");

    // Base case: stack has 1 element, which is the answer => finished
    if (stack.size() == 1)
        System.out.printf("Finished, Answer: %s\n",stack.peek());

    // Recursive case: stack more elements on it.
    if (stack.size() > 1){
        String temp1 = stack.peek();
        stack.pop();
        String temp2 = stack.peek();
        stack.pop();
        String temp3 = stack.peek();
        stack.pop();


            if (temp3.equals("+")){
            float resultant = Float.parseFloat(temp1) + Float.parseFloat(temp2);
            stack.push(String.valueOf(resultant));
            //System.out.println(resultant);
            calculate(stack);
            }

            if (temp3.equals("-")){
            float resultant = Float.parseFloat(temp1) - Float.parseFloat(temp2);
            stack.push(String.valueOf(resultant)); 
            //System.out.println(resultant);
            calculate(stack);
            }

            else if (temp3.equals("*")){
            float resultant = Float.parseFloat(temp1) * Float.parseFloat(temp2);
            stack.push(String.valueOf(resultant)); 
            //System.out.println(resultant);
            calculate(stack);
            }

            else if (temp3.equals("/")){
            float resultant = Float.parseFloat(temp1) / Float.parseFloat(temp2);
            stack.push(String.valueOf(resultant)); 
            //System.out.println(resultant);
            calculate(stack);
            }

            else{
            System.out.printf("Something severely has gone wrong.");
            }
        }  
    }
}

输入和错误:

:~ Home$ java stacks2
Enter a math equation in reverse polish notation:
4 5 * 6 -
Finished, Answer: 4
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:85)
at stacks2.calculate(stacks2.java:41)
at stacks2.main(stacks2.java:22)

显然,这只是第一个元素,这让我认为我在 17 处的 while 循环是原因。有什么见解吗?

4

3 回答 3

5

String in = input.next();读你一个词,然后你试图标记那个词。也许你的意思是String in = input.nextLine();

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next() http://docs.oracle.com/javase/1.5.0/docs/api /java/util/Scanner.html#nextLine()


此外,您的代码中有这两行。

if (!stack.isEmpty())
  // throw new StackUnderflowException("Empty Stack");

这是完全错误的。没有大括号,if影响下一条语句。这不是评论 - 它是以下如果。

这个:

if (!stack.isEmpty())
// throw new StackUnderflowException("Empty Stack");

// Base case: stack has 1 element, which is the answer => finished
if (stack.size() == 1)
    System.out.printf("Finished, Answer: %s\n",stack.peek());

相当于:

if (!stack.isEmpty())
    if (stack.size() == 1)
        System.out.printf("Finished, Answer: %s\n",stack.peek());

和这个:

if (!stack.isEmpty() && stack.size() == 1){
    System.out.printf("Finished, Answer: %s\n",stack.peek());
}

道德:始终使用带有 AND 的大括号,if不要注释掉断言。即使您确实注释掉了断言,也要完整地注释它们,而不是其中的一半,尤其是当另一半是未加括号的 if 时。


第三,你的逻辑有问题。你来做这件事:

将所有符号推入堆栈,然后弹出前三个并将它们视为运算符和两个数字。如果您改用队列,这将适用于某些输入。

4 5 * 6 -

按照您的逻辑,这将弹出* 6 -并崩溃。如果您使用队列,它将在这种情况下工作

4 5 * 6 - 
20 6 -
14

但不是这种情况:

(1+1)*(1+1)
express as RPN
1 1 + 1 1 + *
2 1 1 + *

接下来,您弹出 2 1 1 并崩溃。

相反,你应该做什么:

Read the input. For each symbol:
  if it is a number,
    push it on the stack.
  else,
    pop two numbers from the stack,
    perform the operation and
     push the result.
于 2012-10-25T07:10:54.933 回答
0

堆栈是 LIFO,或“后进先出”。因此,当您有一个输入序列4 5 * 6 -并执行以下操作时:

rpnStack.push(st.nextToken());

你弹出的第一件事是“-”,第二件事是“6”,第三件事是“*”。这是你所期望的吗?

此外,而不是:

String temp1 = stack.peek();
stack.pop();

你可以做:

String temp1 = stack.pop();
于 2012-10-25T07:15:41.630 回答
0
import logging, sys, time
import jenkins from jenkinsapi.jenkins 
import Jenkins from jenkinsapi.build 
import Build from collections import OrderedDict

LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
于 2017-03-23T10:20:44.900 回答