I want to make a stack in Java without using built in class provided by the util package. I wrote this code but it throws a NullPointerException everytime I run it. I made two classes. The first one that that contains the method and the logic of stack i.e Push and Pop and method for checking empty and full of stack;
private int MaxStack;
private int emptyStack;
public static int top;
private char[] items;
public SimpleStack(int i) {
// TODO Auto-generated constructor stub
}
public void Stack(int i)
{
MaxStack=i;
emptyStack=-1;
top=emptyStack;
items=new char[MaxStack];
}
public void Push( char c){
items[top]=c;
top++;}
public char Pop(char c){
return items[top--];}
public boolean full(){
return top+1==MaxStack;}
public boolean empty(){
return top== emptyStack;}}
The second class contains the main method to run the code:
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
SimpleStack ab=new SimpleStack(10);
char ch;
while((ch= (char)System.in.read())!='\n')
{
if(!ab.full()){
ab.Push(ch);
}
}
while(!ab.empty())
{
System.out.println(ab.Pop(ch));
System.out.println();
}
}
}