//QueueTest.java //enqueue and dequeue strings to/from a queue. //the queue can be bounded or unbounded in size. //LinkedList is used as the queue. //Its addLast() is the enqueue operation // (end of the LinkedList is the tail of the queue). //Its removeFirst()is the dequeue operation // (front of the LinkedList is the head of the queue). import java.util.*; import javax.swing.*; public class QueueTest { public static void main(String[] args) { String input, userCommand, headOfQueue, newTailOfQueue; char op; int userAnswer; int queueMaxSize=-1; //fakeout compiler boolean isQueueBounded; LinkedList myQueue = new LinkedList(); //***create empty queue userAnswer = JOptionPane.showConfirmDialog(null, "Do you want a bounded size queue?", "", JOptionPane.YES_NO_OPTION); if (userAnswer == JOptionPane.YES_OPTION) { input = JOptionPane.showInputDialog("Enter (maximum) size of queue"); queueMaxSize = Integer.parseInt( input ); isQueueBounded = true; } else isQueueBounded = false; printQueue( myQueue ); //show queue at every operation do { userCommand = JOptionPane.showInputDialog( "Enqueue or Dequeue or Quit" ); op = userCommand.toUpperCase().charAt(0); if (op == 'E') { if (isQueueBounded && myQueue.size()==queueMaxSize) //*** System.out.println(" Queue is full! Can not enqueue."); else { newTailOfQueue = JOptionPane.showInputDialog("Enter string to enqueue"); myQueue.addLast(newTailOfQueue); //***** enqueue } } else if (op == 'D') { if (!myQueue.isEmpty()) { //***** check queue (LinkedList) is not empty //***** dequeue Obect cast to needed type: headOfQueue = (String) myQueue.removeFirst(); System.out.println("Dequeued: " + headOfQueue); } else System.out.println(" Queue is empty! Nothing to dequeue."); } printQueue( myQueue ); //show queue at every operation } while (op != 'Q'); System.exit(0); } static void printQueue( LinkedList q) { System.out.print("Queue is: "); //don't normally iterate over a queue. here for illustration purposes. Iterator items = q.iterator(); while (items.hasNext()) System.out.print(items.next()+" "); System.out.println(); } }