UNB/ CS/ David Bremner/ teaching/ old/ cs1083/ java/ CircularQueue.java
import java.util.ArrayList;
import java.util.Scanner;

public class CircularQueue<T> implements Queue<T> {

    private ArrayList<T> data;

    // next element to write (enqueue)
    private int tail;

    // next element to read (dequeue)
    private int head;

    // How many elements;
    private int size, capacity;

    public CircularQueue(int capacity) {
        data = new ArrayList<T>(capacity);
        this.capacity=capacity;
        size = 0;
        tail=0;
        head=0;
    }

    public int size() { return size; }

    public boolean isEmpty() {return size==0; };

    public T front() throws QueueEmptyException {
        if (isEmpty())
            throw new QueueEmptyException("Front of empty queue");

        return data.get(head);
    };


    public void enqueue (T element) throws QueueFullException {
        if (size == capacity)
            throw new QueueFullException("Queue capacity exceeded");

        data.add(tail,element);
        tail=(tail+1) % capacity;
        size++;
    }
    public T dequeue()  throws QueueEmptyException {
        if (isEmpty())
            throw new QueueEmptyException("dequeue from empty queue");

        T retval = data.get(head);
        head = (head+ 1) % capacity;
        size--;
        return retval;
    }


    public static void main(String[] args){
        String sentence = "Shooby doo wop she bop" ;
        Scanner words =new Scanner(sentence);

        Queue<String> queue=
            new CircularQueue<String>(5);
        while(words.hasNext()){
            String word=words.next();
            queue.enqueue(word);
        }
        while(!queue.isEmpty()){
            System.out.println(queue.dequeue());
        }
    }

}