【问题标题】:'If' condition doesn't work with the stack pop and peek methods inside the if condition in java'If'条件不适用于java中if条件内的堆栈弹出和peek方法
【发布时间】:2020-06-29 19:28:37
【问题描述】:
    Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    if (st.pop() == st2.peek()) {
        System.out.println("same");
    }

上面的代码应该打印“same”,但由于 if 条件失败而无法执行。

Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    int temp = st.pop();
    int temp2 = st2.peek();
    if (temp == temp2) {
        System.out.println("same");
    }

但是当我将 pop 和 peek 函数值存储在临时变量中时,if 条件返回 true。 pop 和 pop 函数似乎存在问题。

我为找到我的愚蠢错误所做的事情(因为我知道我犯了很多错误):

  • 将推送的值更改为不同的值。我发现当我使用任何高于 127 的数字或低于 -127 的任何数字时,if 条件都会失败。

  • 将 pop 和 peek 值存储在似乎可以解决问题的临时值中。但是仍然没有解释为什么 if 条件失败的问题。

谁能帮我弄清楚为什么会这样。我错过了什么愚蠢的东西吗?提前谢谢你。

【问题讨论】:

    标签: java if-statement stack


    【解决方案1】:

    好的,让我们从这个开始

    if (st.pop() == st2.peek()) {
            System.out.println("same");
    }
    

    使用此代码您可以创建Integer == Integer。不行,你得用equals比较一下

    链接:Java: Integer equals vs. ==

    有了这个,你比较 2 个整数是可以的

    if (temp == temp2) {
            System.out.println("same");
    }
    

    解决方案:

    if (st.pop().equals(st2.peek())) {
                System.out.println("same");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2022-06-28
      相关资源
      最近更新 更多