加入队列时如何避免java.lang.ArrayIndexOutOfBoundsException



我正在为我的数据结构类做一个简单的(?(练习。它一直工作得很好,直到我有一个元素离开队列,然后尝试添加另一个元素,这时我会得到以下错误:

线程中的异常"主";java.lang.ArrayIndexOutOfBoundsException:索引10超出长度10的界限at queueExercise.InterQueue.join(IntegerQueue.java:20(at queueExercise.InterQueueTest.main(IntegerQueueTest.java:27(

我的代码如下:

队列构造函数类:


public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int  newValue) {

if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}

}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else 
return false;

}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}

public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}

测试类


public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();

q.join(112);

q.leave();
q.leave();
q.leave();

q.printQueue();

q.join(112);
q.join(254);

q.printQueue();
}


}

问题出在联接方法中,更确切地说,出在条件if (end == queue.length)中。您所要做的就是将其更改为if (end == queue.length - 1)

相关内容

最新更新