我想在堆棧上進行push和pop操作,並嘗試從堆棧中彈出最小元素。它顯示空指針異常。我試着調試它。但仍然是拋出空點異常。線程主例外。 NullPointException
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Stacks {
static void Stack_Push(Stack<Integer> SP, int a)
{
SP.push(new Integer(a));
System.out.println("stack: " + SP);
}
static void stack_pop(Stack<Integer> SP) {
System.out.print("Popping Minimum Element ");
int n = 0, k = 0;
final int [] pop_array = null;
while (!SP.empty()){
int pop_elem = SP.pop();
pop_array[k++] = pop_elem;
}
for (int i = 1; i < n; i++) {
int j = i;
int B = pop_array[i];
while ((j > 0) && (pop_array[j-1] > B)) {
pop_array[j] = pop_array[j-1];
j--;
}
pop_array[j] = B;
}
System.out.println("stack: " + pop_array[0]);
}
public static void main(String args[]) throws IOException {
Stack<Integer> st = new Stack<Integer>();
int num, n;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.print("Enter number of elements : ");
String str = bf.readLine();
num = Integer.parseInt(str);
for(int i = 0; i < num; i++){
System.out.print("Enter elements : ");
str = bf.readLine();
n = Integer.parseInt(str);
Stack_Push(st, n);
}
stack_pop(st);
try {
stack_pop(st);
}
catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
請張貼例外本身,讓我們知道哪些線把它扔。 – paislee 2012-03-20 18:29:58
bf.readLine也可能返回null – assylias 2012-03-20 18:39:39