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

Design a class that stores strings on a dynamic queue. The strings should not be

ID: 3715837 • Letter: D

Question

Design a class that stores strings on a dynamic queue. The strings should not be fixed in length. Demonstrate the class with a driver program.

1. Make the isFull member private.

2. Define a queue overflow exception and modify enqueue so that it throws this exception when the queue runs out of space.

3. Define a queue underflow exception and modify dequeue so tht it throws this exception when the queue is empty.

4. Rewrite the main program so that it catches overflow rxceptions when they occur. The exception handler for queue overflow should print an appropriate error message andthen terminate the program.

Explanation / Answer

import java.util.*;

import java.lang.*;

import java.io.*;

class Queue

{

// Queue implemented using linked list. "Element" is a single node of the linked list.

// It has a data field, and a pointer to the next Element.

private static class Element<String> {

private String data;

private Element<String> link;

}

private Element<String> head, tail;

private int number, size;

public Queue(int s) {

this.head = null; // Head of the queue

this.tail = null; // Tail of the queue

this.number = 0; // Number of items in the queue

this.size = s; // Maximum size of queue

}

public int getSize() {

return this.size;

}

private boolean isFull() {

return number == size;

}

public boolean isEmpty() {

return head == null;

}

public void enqueue(String str) {

if (isFull()) throw new IndexOutOfBoundsException("Queue overflow");

// Adds element to end of the queue. Creates new element, and it is pointed to by the last element in queue(tail)

Element<String> last = tail;

tail = new Element<String>();

tail.link = null;

tail.data = str;

if (isEmpty()) {

head = tail;

} else {

last.link = tail;

}

number++;

}

public String dequeue() {

if (isEmpty()) throw new NoSuchElementException("Queue underflow");

// Remove from front of the queue.

String s = head.data;

head = head.link;

number--;

if (isEmpty()) tail = null;

return s;

}

public static void main (String[] args) throws Exception

{

// your code goes here

Queue q = new Queue(4);

q.enqueue("Hello");

q.enqueue("World");

String>

q.enqueue("Java");

q.enqueue("JVM");

q.enqueue("String");

try {

q.enqueue("NewString");

} catch(NoSuchElementException e) {

System.out.println(e);

System.exit(0);

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote