For the following code Modify add and poll methods The front
For the following code:
Modify add() and poll() methods. The front and rear indices need to circle back to index 0 whenever the end of the array is reached. Modify the print() method accordingly.
Solution
Answer:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package main;
/**
 *
 * @author Elixir_Black
 */
 /*For the following code :
 Modify add() and poll() methods.
 The front and rear indices need to circle back to index 0 whenever the end of the array is reached.
 Modify the print() method accordingly.
 */
 class ArrayQueue {
    private int data[];
    private int capacity = 100; //maximum capacity for this queue
    private int front; //index of front of queue
    private int back; // index of back of queue
    private int length;
   //constructor
    public ArrayQueue(){
        data = new int[capacity];
        front = 0;
        back = 0;
        length = 0;
    }
   //add an item to the queue
    public void add(int value){
        //add to the back
   
        if (back < capacity){
            data[back] = value;
            back++;
            length++;
        }
        else{
            System.out.println(\"reached maximum capacity\");
        }
    }
public void poll(){
        //add to the back
 if (data[0]==-1){
 System.out.println(\"Queue is empty\");
 }
 else {
 if (front < capacity && front>=0){
 data[front] = -1;
 length--;
 int counter = 1;
 for (int i = 0;i<length;i++){
 data[i] = data[counter];
 data[counter]=-1;
 counter++;
 }
 back--;
 }
 else{
 System.out.println(\"reached maximum capacity\");
 }
 }
    }
   public boolean isEmpty(){
        return (length == 0);
    }
   //print the values of the queue
    public void print(){
        for (int i = front; i < back; i++){
            System.out.print(data[i] + \" \");
        }
        System.out.println();
    }
 }
 public class Part2 {
    public static void main(String[] args){
        int i;
        ArrayQueue q = new ArrayQueue();
        for (i = 0; i<100; i++){
            q.add(i);
        }
        q.add(100);// should print a message, maximum capacity
        q.poll();
        q.add(100);
        for (i = 0; i<95; i++){
            q.poll();
        }
        q.print(); // should print 96 97 98 99 100
        q.add(200);
        q.add(300);
        for (i = 0; i<7; i++)
            q.poll();
        q.poll(); // should print a message, queue is empty
        for (i = 0; i<10; i++)
            q.add(i + 1);
        q.print(); //should print the numbers from 1 to 10
    }
 }



