Exercise files:
QueueFullException.java
QueueEmptyException.java
FixedQueue.java
QExcDemo.java
In this project, two custom exceptions were created for the queue class (Queue), which indicate error conditions for full queue and empty queue. These exceptions are used by the put() and get() methods.
Queue Exceptions:
FixedQueue Class Implementation:
Exceptions and FixedQueue Class Code:
QueueFullException.java
public class QueueFullException extends Exception { int size; QueueFullException(int s) { size = s; } public String toString() { return "\nQueue is full. Maximum size is " + size; } }
QueueEmptyException.java:
public class QueueEmptyException extends Exception { public String toString() { return "\nQueue is empty."; } }
FixedQueue.java:
class FixedQueue implements ICharQ { private char q[]; private int putloc, getloc; public FixedQueue(int size) { q = new char[size]; putloc = getloc = 0; } public void put(char ch) throws QueueFullException { if (putloc == q.length) throw new QueueFullException(q.length); q[putloc++] = ch; } public char get() throws QueueEmptyException { if (getloc == putloc) throw new QueueEmptyException(); return q[getloc++]; } }
Testing with QExcDemo:
The QExcDemo class simulates the use of the queue:
Inserts elements until exceeding the limit, throwing QueueFullException.
It tries to remove elements from an empty queue by throwing QueueEmptyException.
class QExcDemo { public static void main(String args[]) { FixedQueue q = new FixedQueue(10); char ch; int i; try { for(i=0; i < 11; i++) { System.out.print("Attempting to store : " + (char) ('A' + i)); q.put((char) ('A' + i)); System.out.println(" - OK"); } } catch (QueueFullException exc) { System.out.println(exc); } try { for(i=0; i < 11; i++) { System.out.print("Getting next char: "); ch = q.get(); System.out.println(ch); } } catch (QueueEmptyException exc) { System.out.println(exc); } } }
Updated ICharQ Interface:
ICharQ now contains throws exceptions in the put() and get() methods, reflecting the exceptions thrown by FixedQueue.
public interface ICharQ { void put(char ch) throws QueueFullException; char get() throws QueueEmptyException; }
Expected Output:
The program displays messages indicating the success of element insertions and removals, as well as error messages:
Queue is full. Maximum size is 10 when the queue is full.
Queue is empty. when trying to remove an element from an empty queue.
The above is the detailed content of Try This Add exceptions to the Queue class. For more information, please follow other related articles on the PHP Chinese website!