当我调用toString()方法时,如果索引回绕之后(前>后),它将不起作用。我已包含以下代码。之后,我进入队列(5)和进入队列(6),toString似乎被完全忽略了。起初,我以为我没有覆盖Java中的默认toString,但第一个print语句清楚地告诉了我。无论如何,请检查代码:
public class driver {
public static void main(String[] args) {
Queue queue = new Queue(4);
System.out.println(queue);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
System.out.println(queue);
queue.dequeue();
System.out.println(queue);
queue.dequeue();
System.out.println(queue);
queue.enqueue(5);
queue.enqueue(6);
System.out.println(queue);
}
public static class Queue {
int front;
int rear;
int capacity;
int[] queue;
public Queue(int size) {
this.capacity = size;
this.front = this.rear = -1;
this.queue = new int[capacity];
}
@Override
public String toString() {
String str = "";
if (front > rear) {
int i = front;
while (i != rear) {
str = str + queue[i % queue.length] + " ";
i++;
}
//str= str+queue[rear];
}
if (front < rear) {
for (int i = front; i <= rear; i++) {
str = str + queue[i];
}
}
if (front == rear) {
str = "This Queue is Empty. Please Enqueue";
}
return str;
}
public boolean isFull() {
return ((rear == this.queue.length - 1 && front == 0) || rear == front - 1);
}
public boolean isEmpty() {
return (front == -1);
}
public void enqueue(int elem) {
if (isFull()) {
System.out.println("Full Queue - dequeue an element if you need to add an element in the queue");
} else {
if (isEmpty()) {
this.queue[++rear] = elem;
front = 0;
} else {
rear = (rear + 1) % this.queue.length;
this.queue[rear] = elem;
}
}
}
public int dequeue() {
if (isEmpty()) {
System.out.println("empty queue. Enqueue some elments. ");
return -1;
} else {
int store = this.queue[front];
if (rear == front) {
front = rear = -1;
} else {
front = front + 1 % this.queue.length;
}
return store;
}
}
}
*这里有一个大括号,对于发布问题来说还是很新的。 PS可以帮助我,因为显然我在问题中张贴了太多代码。有任何解决方法吗?
答案 0 :(得分:1)
问题出在toString的while循环中的i++
。
请考虑front = 3
和rear = 1
的情况,然后从i = front = 3
开始循环。但是,您会不断递增,直到达到i == rear
,此情况自rear < front
您想要的是让i
到达0
后返回到capacity
。
您可以删除i++
并将其替换为i = (i + 1) % capacity;
似乎您的代码中存在另一个错误,因为当我运行它时,我会看到
This Queue is Empty. Please Enqueue
1234
234
34
3 4 5
您需要自己弄清楚这一点。
您甚至可以将其压缩为一个for语句
for(int i = front; i != rear; i = (++i) % capacity)