Cod*_*rji 0 java stack nullpointerexception
我是java的新手,我正在尝试编写一个Linked-List Stack ..
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
现在当我通过main.main中的Execption java.lang.NullPointerException输入一个数字编译器时(main.java:18)
为什么会这样,以及如何避免它请耐心等待,并提前致谢
ob调用push时,您的堆栈为空.你需要实例化它.代替
Stack ob=null;
Run Code Online (Sandbox Code Playgroud)
你需要拥有
Stack ob = new Stack();
Run Code Online (Sandbox Code Playgroud)