当我调用我的 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有人可以帮助我,因为显然我在我的问题中发布了太多代码。任何解决方法?