简体   繁体   中英

Stack program in Java without using built-in classes

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 ie 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();
}


}
}

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.

尝试将Stack(int)中的逻辑移动到SimpleStack(int)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM