Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone fix this code for me so that I dont have to do size + 1 and queue =

ID: 3861037 • Letter: C

Question

Can someone fix this code for me so that I dont have to do size + 1 and queue = new String[6] in the contructors to get the result I want? It works but only when I do this and id like the constructors to stay the same but I cant figure out where I messed up.

public class MinimalQueue {

String queue[];

int front = -1;

int back = -1;

public MinimalQueue(){
queue = new String[5];
}
  
public MinimalQueue(int size) {

queue = new String[size];

}

public void enqueue(String element) {

back = (back + 1) % queue.length;

queue[back] = element;

if (front == -1) {
front = 0;
}

}

public String dequeue() {

String element = queue[front];

queue[front] = null;

if (front == back) {
front = back = -1;
} else {
front = (front + 1) % queue.length;
}

return element;

}

public boolean isFull() {

return back == queue.length - 1;

}
  
public boolean isEmpty() {

return front == -1;

}

public void showQueue() {

for (int i = front; i <= back; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();

}

}

Explanation / Answer

Here is the modified version for you:

public class MinimalQueue {
   String queue[];
   int front = -1;
   int back = -1;
   public MinimalQueue()   {
       queue = new String[5];
   }
  
   public MinimalQueue(int size) {
       queue = new String[size];
   }
  
   public void enqueue(String element) {
       back = (back + 1) % queue.length;   //Calculates the back index.
       queue[back] = element;               //Inserts the element at the back.
       /* This should not be done. Actually, inserting an element at the back, should not
       modify the front index.
       if (front == -1) {
           front = 0;
       }*/
   }
  
   public String dequeue() {
       front = (front + 1) % queue.length;   //Calculates the front index.
       String element = queue[front];   //Copies the queue front to element.
       queue[front] = null;           //Makes the queue front empty.
       if (front == back) {           //If no elements in queue, re-initialize queue indices.
           front = back = -1;
       }
       return element;
   }
  
   public boolean isFull() {
       return back == queue.length - 1;
   }
  
   public boolean isEmpty() {
       return front == back;
   }
  
   public void showQueue() {
       for (int i = front+1; i <= back; i++) {
           System.out.print(queue[i] + " ");
       }
       System.out.println();
   }