的EmptyStackException(EmptyStackException)

2019-07-02 14:25发布

这的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循环事业的第一要素。 任何见解?

Answer 1:

String in = input.next(); 你读一个词,那么你正试图tokenise这个词。 也许你的意思是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());
}

道德:总是使用大括号有if ,不注释掉断言。 即使你注释掉断言,完全评论他们,而不是一个一半的人,epecially当另一半是,如果一个未加括号。


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

推动所有符号栈,然后弹出的前三名,并考虑他们的操作员和两个数字。 这将有一些投入工作,如果你使用一个队列来代替。

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.


Answer 2:

堆栈是后进先出法,即“后进先出”。 所以,当你有一个输入序列4 5 * 6 -而做到这一点:

rpnStack.push(st.nextToken());

你弹出的第一件事将是“ - ”,第二件事情将是“6”,而第三件事将是“*”。 这是你期待什么?

此外,而不是:

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

你可以做:

String temp1 = stack.pop();


Answer 3:

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)


文章来源: EmptyStackException
标签: java stack