Reputation: 4264
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();
}
}
}
Upvotes: 0
Views: 5726
Reputation: 1904
As others have stated, your constructor isn't doing anything. But another issue I see is that even if you move your logic in Stack(int) to SimpleStack(int), you are still setting your int "top" to equal "emptyStack", which is -1. So now when you push an item onto your array, you are initially trying to push it into items[-1], which is obviously going to throw an error. Carefully step through your code line by line and you will be able to see exactly what is going on.
Upvotes: 0
Reputation: 533660
The problem is that your constructor doesn't do anything.
It appears you have another method public void Stack(int i)
which should be the constructor instead.
I want to make a stack in Java without using built in class provided by the util package.
Even so, you should read the code for the built in Stack class as you could learn something useful, like using standard formatting and coding conventions.
Upvotes: 4