when I call my toString() method it doesn't work if after the index wraps around (front > rear). I have included the code below. After, I enqueue(5) and enqueue(6), the toString seems to be completely ignored. At first I thought I wasn't overriding the default toString in Java but the first print statement clearly tells me I am. Anyways, check the code out:
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;
}
}
}
*there is a return curly bracket here too lol still new to posting questions. P.S can someone help me because apparently I posted too much code in my question. Any workarounds?
ishould be decremented instead of incremented in the first case. (istarts out asfront, and then you add one to it and see if it is equal torear, butfront > rearalready... I am surprised you don't just enter an infinite loop there)