java 堆栈作业 将数字放入堆栈

标签 java stack

大家好,需要帮助回答有关 java 堆栈中的问题

这是我的问题: 完成下面的方法,该方法计算表示反波兰(后缀)表示法的算术表达式的字符串。该字符串包含一个由数字“0”到“9”和运算符“+”、“-”、“*”和“/”组成的表达式。

例如,以下是一些可能的输入字符串和相应的结果:

输入: 输出: “12+”3
“43*”12
“123+”5
“123+”7
“12+3*”9
为了帮助您解决这个问题,您可以使用标准类 Stack,它实现了整数堆栈:

Stack<Integer> stk = new Stack<>(); // create a stack
stk.push(5);                        // push an integer onto the top of the stack
int n = stk.pop();                  // pop an integer from the top of the stack
if ( stk.empty() ) ...              // test if the stack is empty

我开始回答这是我的代码:

    Stack<Integer> stk = new Stack<>();

int res=0;

        for (int i = 0; i < expression.length(); i++) {
            char ch = expression.charAt(i);

            if (Character.isDigit(ch)) {
                stk.push(ch - '0');
            } 
else {
                if(stk.isEmpty())
            {
                return 0;
            }

                if (ch == '-') {
                    res = stk.pop() - stk.pop();
                    res=res*-1;
                }

                if (ch == '*') {
                    res = stk.pop() * stk.pop();
                }


                if (ch == '+') {
                    res = stk.pop() + stk.pop();
                }
                if (ch == '/') {
                    res = stk.pop() / stk.pop();
                }
            }

}


     return res;

这是我收到的错误,我不明白这段代码中有什么问题。

错误:

 An exception of type java.util.EmptyStackException was reported when executing this line:

    res = stk.pop() * stk.pop();

Exception in thread "main" java.util.EmptyStackException
    at java.util.Stack.peek(Stack.java:102)
    at java.util.Stack.pop(Stack.java:84)
    at Main.evaluate(Main.java:28)
    at Main.exitTest(Main.java:78)
    at Main.main(Main.java:104)

我需要你们的帮助,谢谢大家。

最佳答案

要检查堆栈是否为空,请使用 stk.isEmpty()。

对于计算,从堆栈中弹出两个项目,对它们进行计算,然后将其压入堆栈。例如乘法:

if (ch == '*') {
    stk.push(stk.pop() * stk.pop());
}

关于java 堆栈作业 将数字放入堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032488/

相关文章:

java - 如何从 Eclipse IDE 获取当前 Activity 选项卡的文件名?

java - 服务器到客户端通知/Web 服务(jax-ws) 到客户端通信

c++ - 扩展 std::unordered_set<> 以与 std::stack<> 一起使用

c++ - 当 SIGABRT 发生时,堆栈会被展开吗?

java - 多键、链接哈希

java.lang.classnotfoundexception org.springframework.web.servlet.dispatcherservlet

java - Java跨IDE插件开发可以吗?

java - java.util.Set 中的重复元素

c - 是否可以从标准 C 中的堆栈执行代码?

C++ 堆栈使用模板化链表 - 内存泄漏