I am new at java and I am trying to write a 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;
}
}
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);
}
now when I enter a number the compiler through
an Execption java.lang.NullPointerException
at main.main(main.java:18)
Why this is happening and how to avoid it
Please be patient and thanks in advance
Your stack
obis null when you call push. You need to instantiate it. Instead ofyou need to have