【发布时间】: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