-1

I am trying to implement stack but getting this error. I can not understand why I am getting this because I defined the size of an array. my Error : java.lang.ArrayIndexOutOfBoundsException

ReverseStack(int n){
        top = - 1;
        size = n;
        a = new char[size];

    }
    boolean push(char c){
        if(top >=size ){
            System.out.println("Stack overflow");
            return false;
        }else{
            a[top++] = c;
            return true;
        }
    }
    char pop(){
        if(top<0){
            System.out.println("Stack underflow");
            return 0;
        }else{
            char c = a[top--];
            return c;
        }
    }

Method from where I am calling push operation.

public static void reverse(StringBuffer str){
        int n = str.length();
        ReverseStack obj = new ReverseStack(n);
        int i;
        for(i=0; i<n; i++){
            obj.push(str.charAt(i));
        }
        for(i=0; i<n; i++){
            char ch = obj.pop();
            str.setCharAt(i, ch);
        }
    }

Can some one please help me in that. Any code changes or new techniqe must be appriciated.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
shanky singh
  • 1,121
  • 2
  • 12
  • 24

1 Answers1

4

you starting your attribute top as -1

either

1- top = 0; on constructor

or

2- in push and pop method use ++top and --top

see How do the post increment (i++) and pre increment (++i) operators work in Java? for more info about the difference

nafas
  • 5,283
  • 3
  • 29
  • 57