0

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

4

1 回答 1

1

问题出i++在您的 toString 的 while 循环中。

考虑用 .开始循环的front = 3情况。但是,您会不断增加,直到达到为止,这将永远不会发生rear = 1i = front = 3i == rearrear < front

你想要的是 fori循环回到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)
于 2019-07-15T18:59:23.363 回答