EmptyStackException

use*_*111 3 java stack

此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.");
            }
        }  
    }
}
Run Code Online (Sandbox Code Playgroud)

输入和错误:

:~ 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)
Run Code Online (Sandbox Code Playgroud)

显然,这只是第一个要素,这使我认为我在17岁时的while循环是原因。有见识吗?

Joh*_*rak 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");
Run Code Online (Sandbox Code Playgroud)

这是完全错误的。如果没有大括号,则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());
Run Code Online (Sandbox Code Playgroud)

等效于此:

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

和这个:

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

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


第三,你的逻辑是有缺陷的。你做这个:

将所有符号压入堆栈,然后弹出前三个符号,并将其视为一个运算符和两个数字。这将与一些投入,如果你使用一个队列来代替。

4 5 * 6 -
Run Code Online (Sandbox Code Playgroud)

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

4 5 * 6 - 
20 6 -
14
Run Code Online (Sandbox Code Playgroud)

但是不是这种情况:

(1+1)*(1+1)
express as RPN
1 1 + 1 1 + *
2 1 1 + *
Run Code Online (Sandbox Code Playgroud)

接下来,您弹出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.
Run Code Online (Sandbox Code Playgroud)