Question

TestQueue.java Design a class named Queue for storing integers. Like a stack, a queue holds elements....

TestQueue.java

Design a class named Queue for storing integers. Like a stack, a queue holds elements. But in a queue, the elements are retrieved in a first-in first-out fashion. The class contains:

An int[] data field named elements that stores the int values in the queue.

A data field named size that stores the number of elements in the queue.

A constructor that creates a Queue object with default capacity 8.

The method enqueue(int v) that adds v into the queue.

The method dequeue() that removes and returns the element from the queue.

The method empty() that returns true if the queue is empty.

The method getSize() that returns the size of the queue.

Implement the class with the initial array size set to 8. The array size will be doubled once the number of elements exceeds the size. After an element is removed from the beginning of the array, you need to shift all the elements in the array one position to the left.

Write a test program that adds 20 numbers from 1 to 20 into the queue then removes these numbers and displays them.

Homework Answers

Answer #1

Summary:

Below Java program is an implementation of Queue with an dynamic array that doubles it size when the array capacity is reached. We have implemented queue operations like enqueue, dequeue, empty and getSize methods.

enqueue adds the given element to the queue.

dequeue removes the element from the queue.

empty checks if the queue is empty or not.

getSize returns the current size of the queue.

Java Program:

--------------------------------------------------------------TestQueue.java-----------------------------------------------------

public class TestQueue {

    private int capacity = 8;
    private int data[];
    private int front = 0;
    private int rear = -1;
    private int size = 0;

    public TestQueue() {
        data = new int[this.capacity];
    }

    /**
     * this method adds element at the end of the queue.
     *
     * @param v new value to add into queue
     */
    public void enqueue(int v) {

        if (isQueueFull()) {
            System.out.println("Queue is full, increasing capacity by double...");
            increaseQueueCapacity();
        }
        rear++;
        if (rear >= data.length && size != data.length) {
            rear = 0;
        }
        data[rear] = v;
        size++;
        System.out.println("Adding: " + v);
    }

    /**
     * this method removes an element from the top of the queue
     */
    public int dequeue() {
        int temp = 0;
        if (empty()) {
            System.out.println("Queue is empty!");
        }
        front++;
        if (front > data.length - 1) {
            temp = data[front - 1];
            size--;
            front = 0;
            return temp;
        }
        temp = data[front - 1];
        size--;
        return temp;

    }

    /**
     * This method checks whether the queue is empty or not
     *
     * @return
     */
    public boolean empty() {
        boolean status = false;
        if (size == 0) {
            status = true;
        }
        return status;
    }

    /**
     *
     * @return the current size of the Queue.
     */
    public int getSize(){
        return this.size;
    }



    /**
     * This method checks whether the queue is full or not
     *
     * @return boolean
     */
    public boolean isQueueFull() {
        boolean status = false;
        if (size == data.length) {
            status = true;
        }
        return status;
    }



    private void increaseQueueCapacity() {

        //create new array with double size as the current one.
        int newCapacity = this.data.length * 2;
        int[] newArr = new int[newCapacity];
        //copy elements to new array, copy from rear to front
        int tmpFront = front;
        int index = -1;
        while (true) {
            newArr[++index] = this.data[tmpFront];
            tmpFront++;
            if (tmpFront == this.data.length) {
                tmpFront = 0;
            }
            if (size == index + 1) {
                break;
            }
        }
        //make new array as queue
        this.data = newArr;
        System.out.println("New array capacity: " + this.data.length);
        //reset front & rear values
        this.front = 0;
        this.rear = index;
    }

    public static void main(String a[]) {

        TestQueue queue = new TestQueue();
        // Adding first 8 elements to the queue
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);
        queue.enqueue(5);
        queue.enqueue(6);
        queue.enqueue(7);
        queue.enqueue(8);


        // Checking the current size of the queue and printing it.
        System.out.println("\nThe current size of Queue: " + queue.getSize());
        System.out.println();

        // Adding one new element to check if queue size doubles.
        queue.enqueue(9);
        queue.enqueue(10);
        queue.enqueue(11);
        queue.enqueue(12);
        queue.enqueue(13);
        queue.enqueue(14);
        queue.enqueue(15);
        queue.enqueue(16);
        queue.enqueue(17);
        queue.enqueue(18);
        queue.enqueue(19);
        queue.enqueue(20);

        // Removing 3 elements from queue.
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());

        // Checking current size
        System.out.println("\nThe current size of Queue: " + queue.getSize());
        System.out.println();

        // Removed remaining elements
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());
        System.out.println( "Removed: " +queue.dequeue());

        // Checking current size
        System.out.println("\nThe current size of Queue: " + queue.getSize());
        System.out.println();
    }
}

Output:

Hope this will help you. Enjoy!!!

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Write recursive method to return true if a given array of integers, named numbers, with n...
Write recursive method to return true if a given array of integers, named numbers, with n occupied positions is sorted in ascending (increasing) order, or returns false otherwise. Array can be empty or not. //PRECONDITION: Varible n denotes the number of occupied positions in the array and must be non-negative. Employee class has method getSalary() that returns employee's salary. // An empty array and an array with single element in it, are sorted. Method isSortedRec must be recursive and returns...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract...
Use Java: Also: Please include screenshots if possible. Create a class called AbstractStackTest. Write an abstract method called makeStack that returns a Stack of Strings. Use the Stack interface as the return type, not a specific implementation! Write a class named NodeStackTest that extends your AbstractStackTest class. Implement the makeStack method to return a NodeStack. Repeat parts 1 and 2 for the Queue interface and the NodeQueue implementation. Write a new stack implementation, ArrayStack. It should be generic and use...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
(JAVA) Why is my toString method not printing out the last node? It will not print...
(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this. package driver; import exception.StackException; import stack.*; public class StackDriver { public static void main(String[] args) throws Exception { StackInterface<Painting> painting = new LinkedStack <Painting>(); try { System.out.println("Peeking at top of player stack.\n" + painting.peek()); }catch (StackException e) { System.out.println(e); System.out.println("Let's double check if it's empty: " + painting.isEmpty()); }...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template <class ItemType> class QueueADT { public:        // Action responsibilities        virtual void resetQueue() = 0;           // Reset the queue to an empty queue.           // Post: Queue is empty.        virtual void add(const ItemType& newItem) = 0;           // Function to add newItem to the queue.           // Pre: The queue exists and is not full.          ...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
Design a Java class named Polygon that contains:  A private int data field named numSides...
Design a Java class named Polygon that contains:  A private int data field named numSides that defines the number of sides of the polygon. The default value should be 4.  A private double data field named sideLength that defines the length of each side. The default value should be 5.0.  A private double data field named xCoord that defines the x-coordinate of the center of the polygon. The default value should be 0.0.  A private double...
You are asked to implement a C++ class to model a sorted array of unsigned integers....
You are asked to implement a C++ class to model a sorted array of unsigned integers. The class is to be used in an embedded application that cannot assume the presence of the STL. The array has to be dynamically allocated in such a way that allows programmers using it to specify the required size. Your class should should: (1) provide the appropriate constructors and destructor; (2) provide methods for updating, and showing numbers in/to the array (e.g., to be...