【发布时间】:2018-01-16 20:40:31
【问题描述】:
我已经创建了一个堆栈。
public class STK {
static int capacity = 0;
STK(int size) {
capacity = size;
}
int stackk[] = new int[capacity];
int top = 0;
public void push(int d) {
if(top < capacity) {
stackk[top] = d;
top++;
} else {
System.out.println("Overflow");
}
}
}
它的实现
public class BasicStackImplementation {
public static void main(String[] args) {
STK mystack = new STK(5);
mystack.push(51);
mystack.push(23);
}
}
当我尝试运行这段代码时,它给出了一个错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at STK.push(STK.java:21)
at BasicStackImplementation.main(BasicStackImplementation.java:6)
【问题讨论】:
-
您将数组大小设置为 0,因此您不能将任何内容放入其中。
int stackk[] = new int[capacity];在您运行构造方法之前执行,当时capacity为 0。
标签: java data-structures stack