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.