我在Java新,我試圖寫一個鏈表棧..我的java代碼有什麼問題?
public class Stack {
private Node first;
private class Node {
int item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push(int item)
{
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
}
public int pop()
{
int item=first.item;
first=first.next;
return item;
}
}
import javax.swing.*;
public class main {
public static void main(String[] args) {
Stack ob=null;
int num=0;
while (true)
{
num=Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
ob.push(num);
if (num==0)
break;
}
int k;
k=ob.pop();
JOptionPane.showMessageDialog(null, k);
}
現在
,當我通過 的Execption顯示java.lang.NullPointerException輸入一個數字,編譯器 在main.main(main.java:18)
爲什麼發生這種情況,以及如何避免它 請耐心等待,在此先感謝
哇!我不知道如果你沒有承包商,你可以像這樣初始化它! – Coderji 2013-02-20 14:38:32
@OsamaEspil如果你沒有定義一個構造函數Java爲你做。有關更多詳細信息,請參閱此[回答](http://stackoverflow.com/a/4488766/264775)。 – thegrinner 2013-02-20 14:45:22