Queue problem...can`t print out
hi all ..could anyone help try to give me some suggestion on the issue that i am stuck on ...i am using queue to store the integer from 1 to 9..and try to use peek to print to out the data that i just pass in the queue..
publicclass QueueTest
{
publicstaticvoid main(String[] args)
{
QueueReferenceBased aQueue =new QueueReferenceBased();
for(int i=0; i < 9; i++)
{
aQueue.enqueue(new Integer(i));
}
try
{
//Object temp;
//temp = aQueue.peek();
System.out.print(aQueue.peek() +" ");
//aQueue.peek();
}
catch( EmptyQueueException eqe)
{
System.out.println(eqe.getMessage());
}
}
}
i got the error as the following
Exception in thread "main" java.lang.NullPointerException
at QueueReferenceBased.peek(QueueReferenceBased.java:90)
at QueueTest.main(QueueTest.java:20)
>Exit code: 1
==============================================
//QueueReferenceBased
publicclass QueueReferenceBasedimplements QueueInterface
{
private Node lastNode;
int numberOfElements;
public QueueReferenceBased()
{
lastNode =null;
numberOfElements = 0;
}
publicint size( )
{
// Description: Determines the number of elements in a queue.
// In other words, the length of a queue.
// Precondition: None.
// Postcondition: Returns the number of elements that are
// currently in the queue.
// Throws: None.
return numberOfElements;
}
publicvoid enqueue(Object newElement)
{
// Description: Adds an element at the back of a queue.
// Precondition: None.
// Postcondition: If the operation was successful,
//newElement is at the back of the queue.
// Throws: None.
Node newNode =new Node(newElement);
if(lastNode ==null)
{
//insertion into empty queue
newNode.setNext( newNode );
}
else
{
newNode.setNext( lastNode.getNext());
lastNode = newNode;
}
numberOfElements++;
}
public Object dequeue()throws EmptyQueueException
{
if (!(numberOfElements == 0))
{
// queue is not empty; remove front
Node firstNode = lastNode.getNext();
if (firstNode == lastNode)// special case?
{
lastNode =null;// yes, one node in queue
}
else
{
lastNode.setNext(firstNode.getNext());
}
return firstNode.getObject();
}
else
{
thrownew EmptyQueueException(" EmptyQueueException on dequeue:" +"queue empty");
}
}// end dequeue
public Object peek()throws EmptyQueueException
{
if (!(numberOfElements == 0))
{
// queue is not empty; retrieve front
Node firstNode = lastNode.getNext();
return firstNode.getObject();
}
else{
thrownew EmptyQueueException("EmptyQueueException on peek:"+"queue empty");
}
}
}// end QueueReferenceBased

