Cosmin Andrei
Cosmin Andrei

Reputation: 9

index 0 out of bounds

I have just started Java.I have some C++ experience.I want to implement a stack class.Here is my class:

public class stack {
   private static int MAX;
   stack(int a)
    {
       MAX = a;//input max size of stack
    }
  stack()
  {
     MAX = 1000;//default max size stack is 1000
  }
   private int[] my_stack = new int[MAX];
   private int top = 0;
   public void push(int x)
   {
       if (this.top > MAX)System.out.println("OVERFLOW");
       else my_stack[this.top++] = x;//ERROR LINE
   }
   public void pop()
   {
       if (this.top == 0)System.out.println("TOO LOW");
       else this.top--;
   }
   public int top()
   {
     return my_stack[this.top - 1];
   }
}

The error says:

Index 0 out of bounds for length 0
    at stack.push(stack.java:17)
    at MainClass.main(MainClass.java:7)

Can anyone explain me the problem?

Upvotes: 0

Views: 98

Answers (1)

Rocco
Rocco

Reputation: 1118

Here some minimal changes, explained with comments

public class stack {
   private int max;  //Removed static here and changed to lowercase, this is an instance field
   stack(int a)
    {
       max = a; //input max size of stack
       my_stack = new int[max]; //Here the value of max is initialized an you can use it
    }
  stack()
  {
     this(1000); //Call other constructor, just to avoid duplicate code
  }
   private int[] my_stack;  //You can't initialize the array there, since you don't know the size yet
   private int top = 0;

   public void push(int x)
   {
       if (this.top >= max)System.out.println("OVERFLOW"); //You must check with >=, not just > since the maximum index is max-1
       else my_stack[this.top++] = x;//ERROR LINE
   }
   public void pop()
   {
       if (this.top == 0)System.out.println("TOO LOW");
       else this.top--;
   }
   public int top()
   {
     return my_stack[this.top - 1];
   }
}

Upvotes: 1

Related Questions