Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created May 14, 2018 16:39
Show Gist options
  • Save yukeehan/d4ada986fcb95355152f51d1e45a2f38 to your computer and use it in GitHub Desktop.
Save yukeehan/d4ada986fcb95355152f51d1e45a2f38 to your computer and use it in GitHub Desktop.
public class GenQDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer iStore[] = new Integer[10];
GenQueue<Integer> q = new GenQueue<Integer>(iStore);
Integer iVal;
System.out.println("Demostrate a queue of Integers.");
try {
for(int i=0; i<5; i++) {
System.out.println("Adding "+ i +" to q.");
q.put(i);
}
}catch(QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for(int i=0; i<5; i++) {
System.out.println("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
} catch (QueueEmptyException e) {
// TODO: handle exception
System.out.println(e);
}
System.out.println();
Double dStore[] = new Double[10];
GenQueue<Double> q2 = new GenQueue<Double>(dStore);
Double dVal;
System.out.println("Demeonstrate a queue of Doubles.");
try {
for(int i=0; i<5; i++) {
System.out.println("Adding "+ (double)i/2 + " to q2.");
q2.put((double)i/2);
}
} catch (QueueFullException e) {
// TODO: handle exception
System.out.println(e);
}
System.out.println();
try {
for(int i=0; i<5; i++) {
System.out.print("Getting next Double from q2 ");
dVal = q2.get();
System.out.println(dVal);
}
}catch(QueueEmptyException e) {
System.out.println(e);
}
}
}
class GenQueue<T> implements IGENQ<T> {
private T q[];
private int putloc, getloc;
public GenQueue(T[] aRef) {
q = aRef;
putloc = getloc = 0;
}
public void put(T obj) throws QueueFullException{
if(putloc == q.length)
throw new QueueFullException(q.length);
q[putloc++] = obj;
}
public T get() throws QueueEmptyException{
if(getloc == putloc)
throw new QueueEmptyException();
return q[getloc++];
}
}
public interface IGENQ<T> {
void put(T ch) throws QueueFullException;
T get() throws QueueEmptyException;
}
public class QueueEmptyException extends Exception {
public String toString() {
return "\nQueue is empty";
}
}
public class QueueFullException extends Exception {
int size;
public QueueFullException(int s) {
size = s;
// TODO Auto-generated constructor stub
}
public String toString() {
return "\nQueue is full. Maximum size is " + size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment