gpt4 book ai didi

java - 尝试使用数组实现循环队列时出现 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-30 07:10:04 24 4
gpt4 key购买 nike

visualization of the queue

以上是作业页面的图表

对于家庭作业,我必须使用数组实现循环队列。除了要附加字符串 "I", "J", "K", "L" 的情况之外,我的所有条件都有效。作为此操作的结果,数组中的一些新值应该循环回到开头。但是,在附加第二个字母时,我收到 ArrayIndexOutOfBoundsException

调试器进一步将问题跟踪到 toString 方法,但我无法理解问题所在。

有什么建议吗?

public class CircularArrayQueueApp {
public static void main(String[] args) {

CircularArrayQueue queue = new CircularArrayQueue(10);

String[] data1 = {"A", "B", "C", "D", "E", "F", "G", "H"};
String[] data2 = {"I", "J", "K", "L"};

for (String aData1 : data1) queue.enqueue(aData1);

System.out.println(queue.first());
System.out.println(queue);

for (int i = 0; i < 4; i++) {
int index = queue.getRead();
System.out.println("\"" + queue.dequeue() + "\" has been dequeued at index " + index);
}

System.out.println(queue.first());
System.out.println(queue);

for (int i = 0; i < 4; i++) {
queue.enqueue(data2[i]);
}

System.out.println(queue.first());
System.out.println(queue);

}

static class CircularArrayQueue {
private final int length;
private int read;
private int write;
private final Object[] data;

public CircularArrayQueue(int size) {
data = new Object[size];
length = data.length;
read = 0;
write = 0;
}

Object read() {
Object o;
o = data[read];
read = (read + 1) % length;

return o;
}

Object first() {
if (isEmpty()) {
System.out.println("**Empty queue**");
return null;
}
return data[read];
}

void write(Object o) {
data[write] = o;
write = (write + 1) % length;
}

boolean enqueue(Object o) {
if (isFull()) {
System.out.println("**Full queue**");
return false;
}
write(o);
return true;
}

public Object[] getData() {
return data;
}

Object dequeue() {
if (isEmpty()) {
System.out.println("**Empty queue**");
return null;
}
return read();
}

boolean isFull() {
return read == (write + 1) % length;
}

boolean isEmpty() {
return read == length;
}

public String toString() {
String output = "[";

for (int i = read; ((i) % length) != write; i++)
output += data[i] + " ";

return output.substring(0, output.length() - 1) + "]";
}

public int getRead() {
return read;
}

public int getSize() {
return length;
}

public int getWrite() {
return write;
}
}
}

最佳答案

您没有修改数组查找的值。还可以尝试使用字符串连接器来简化事情

StringJoiner sj = new StringJoiner(" ", "[", "]");
for (int i = read; i % length != write; i++) {
sj.add(data[i % length].toString());
}
return sj.toString();

或者在增加的同时进行修改

for (int i = read; i != write; i = (i + 1) % length) {
sj.add(data[i].toString());
}

关于java - 尝试使用数组实现循环队列时出现 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39376213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com