Hello,
I have got a Java queue and i want to print out the smallest number in the queue. Right now my program prints out the first number in the queue. Here is the code:
import java.util.ArrayList;
import java.util.Iterator;
public class Assign1 {
private final int MAX_QUEUE_SIZE = 5;
private final int NO_SIMULATIONS_TO_RUN = 7;
private int maxSize;
private double[] queArray;
private int nItems;
/**
* main method
* @param args
*/
public static void main( String args[] ) {
new Assign1().runSimulation();
}
/**
* run a simulation priority queue
*/
public void runSimulation() {
PriorityQueue queue = new PriorityQueue();
initQueue(queue);
for (int i = 0; i < NO_SIMULATIONS_TO_RUN; i++) {
System.out.println( "The numbers in the queue are: " + queue.toString());
System.out.println( "The current dispatched number is " + queue.poll());
queue.remove();
int item = getRandomNumber();
System.out.println( "The new coming number is " + item );
queue.add(item);
System.out.print( "\n\n" );
}
}
/**
* creates and inits a queue
* @param queue
*/
private void initQueue(PriorityQueue queue){
for (int i = 0; i < MAX_QUEUE_SIZE; i++)
queue.add(getRandomNumber());
}
/**
* returns a RandomNumber()
* @return
*/
public static int getRandomNumber(){
return 1 + ( int ) ( Math.random() * 100 );
}
/**
* custom queue class
*/
private class PriorityQueue extends ArrayList {
/**
* allows us to add int values into an ArrayList
* @param val
*/
public void add(int val){
super.add(new Integer(val));
}
/**
* poll for the current top item in the list
* @return
*/
public int poll(){
return ((Integer) iterator().next()).intValue();
}
/**
* returns the items in queue out
* @param queue
*/
public String toString(){
StringBuffer buff = new StringBuffer();
Iterator it = iterator();
buff.append("[");
while (it.hasNext()) {
buff.append(it.next());
if (it.hasNext())
buff.append(", ");
}
buff.append("]");
return buff.toString();
}
/**
* remove the top level item if the list is not empty
*/
public void remove(){
if (!isEmpty())
remove(0);
}
}
}
thanks