一个有关堆栈JAVA的问题,急求解决!

来源:百度知道 编辑:UC知道 时间:2024/09/23 23:29:43
这是我建造的Stack类:
public class Stack {
int cur=0;
int length;
String[] spa=new String[length];
public Stack(int length){}
public void push(String str1){spa[cur]=str1;cur++;}
public String pop(){String s=spa[cur];cur--;return s;}
public String getTop(){return spa[cur];}
public String get(int i){return spa[i];}
public void insert(String str2,int pos){spa[pos]=str2;}
}
然后再引用它:
public class w {
public static void main(String[] args)
{
Stack s=new Stack(5);
s.push("+");
String st=s.pop();
System.out.println("是:"+st);
}
}

运行后提示Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

s.push("+");有错误

public void push(String str1){spa[cur]=str1;cur++;}有错误
怎么回事儿啊?是不是Stack类构造的不对或者调用不对?应该怎么弄啊?

class Stack {
int cur = 0;
int length;
String[] spa;

public Stack(int length) {
this.length = length;
spa = new String[length];
}

public void push(String str1) {
spa[cur] = str1;
cur++;
}

public String pop() {
String s = spa[cur-1];
cur--;
return s;
}

public String getTop() {
return spa[cur];
}

public String get(int i) {
return spa[i];
}

public void insert(String str2, int pos) {
spa[pos] = str2;
}
}

public class w {
public static void main(String[] args) {
Stack s = new Stack(5);
s.push("+");
String st = s.pop();
System.out.println("是:" + st);
}
}