【问题标题】:why wont minVal update? [duplicate]为什么 minVal 不更新? [复制]
【发布时间】:2020-07-03 19:32:20
【问题描述】:

我不明白为什么 MinStack 类中的 minCheck 函数在从 push 函数中调用时没有成功更新 minVal 的值。忽略如果弹出minVal,minVal的值将不代表实际最小值的逻辑错误。

public class MinStack {
    
    int[] array; //array to hold elements
    int n = 0; // number of elements in array
    int minVal=10000; // smallest value in array (initialize to 1000 to prove it wont change)
    
    public int size() { //ignore this useless method
        return n;
    }
    
    
    public void push(int x) {
        if((n+1)>array.length)
            resize();
        array[n] = x;
        n++;
        minCheck(x); // minCheck will check if x is the new smallest value, and set minVal = x if it is.
    }
    
    public int pop() {
        int x = array[n-1];
        n--;
        return x;
    }

    public void minCheck(int x) {
        if(n==1) 
            minVal = x; //if x is the only element in the array, it must be the minVal 
        else {
            if(minVal>x) //if x is smaller than current minVal, it becomes the minVal
                minVal = x;
        }
    }

    private void resize() { //method not relevant to the question
        int[] secondArray = new int[(Math.max(1, n * 2))];
        for(int i=0; i<n; i++) {
            secondArray[i] = array[i];
        }
        array = secondArray;    
    }
    
    public String printMinVal() {
        return "minimum value is: " + minVal;
    }
    
    
    
    public static void main(String[] args) {
        MinStack myStack = new MinStack();
        
        
        try {
        myStack.push(3);
        myStack.push(2);
        myStack.push(1);
        myStack.push(4);
        myStack.push(5);
        myStack.pop();
        } catch(NullPointerException e) {};
        System.out.println(myStack.printMinVal()); //would expect to get "minimum value is 1" as console output, but instead get "minimum value is 1000"
                        
    }
}

【问题讨论】:

  • 永远抓到NullPointerException!并且从不捕获一个异常并且什么都不做,甚至不记录它。

标签: java data-structures logic


【解决方案1】:

发生的情况是您在第一个 push() 中得到了一个 NullPointerException,因为您没有初始化数组。

这里:

public void push(int x) {
    if((n+1)>array.length) //array is null, calling length throws the exception
        resize();
    array[n] = x;
    n++;
    minCheck(x); // minCheck will check if x is the new smallest value, and set minVal = x if it is.
}

您捕获了异常,但不显示它。所以你相信它运行了,但实际上并没有。初始化数组,一切正常。

作为建议,请确保显示所有捕获的异常(通过日志记录,或仅将其打印到控制台),和/或不要在它之后继续该过程,如果它是一个非暂时性错误,例如这个一。不这样做很危险..

【讨论】:

  • 最重要的是:去掉try-catch!
  • 是的,完全同意
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2016-08-06
  • 2017-10-06
  • 2018-05-20
  • 1970-01-01
  • 2019-08-15
相关资源
最近更新 更多