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
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Generate 100 random numbers and add them to a stack and a queue, after print out...
Generate 100 random numbers and add them to a stack and a queue, after print out the content from both stack and queue, sort the data from both in ascending order, then print out again, after being sorted, and go through both the stack a queue and remove an element one at a time till empty then print out a message saying its empty. print out how much time it took to do this process, basically compare the stack and...
Code in Java Create a queue class to store integers and implement following methods: 1) void...
Code in Java Create a queue class to store integers and implement following methods: 1) void enqueue(int num): This method will add an integer to the queue (end of the queue). 2) int dequeue(): This method will return the first item in the queue (First In First Out). 3) void display(): This method will display all items in the queue (First item will be displayed first). 4) Boolean isEmpty(): This method will check the queue and if it is empty,...
Using a queue and a stack, implement a method that tests whether a sequence of numbers...
Using a queue and a stack, implement a method that tests whether a sequence of numbers is a palindrome, that is, equal to the sequence in reverse. For example, [1,2,3,2,1] is a palindrome, but [1,2,2,3,1] is not. Complete the following file: QueueStackUtil.java import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class QueueStackUtil { public static boolean isPalindrome(int[] values) { Queue<Integer> queue = new LinkedList<Integer>(); Stack<Integer> stack = new Stack<Integer>(); for (int s : values) { // insert s into the queue...
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...
Trace the C++ program below showing all output in the order that it is displayed. If...
Trace the C++ program below showing all output in the order that it is displayed. If anything happens that makes it impossible to accomplish an operation or the results of so doingare unpredictable, describe what happens and abort the program at that point. Assume the Queue class is fully defined in an appropriate header and implementation file. The effect of the functions (methods) is as follows - Constructor - creates an empty queue #include <iostream> #include using namespace std; #include...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your Stack class by determining if the following strings have matching open and closing ( ) and/or [ ] and/or { }. To test matches, push open (, [, { onto the stack. Input a close char, pop off the stack and see if input matches symbol form stack.   Use the following data to test your code:                               ( )                               [ ] ( )...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program. Ex. If the input is Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1 the output is Stack contents (top to bottom): 1 Stack...