2015-08-04 3 views
1

Я включил все внутри моей toString, чтобы попытаться получить результат, который я хотел, но мне не повезло. Я пытаюсь получить этот результат:Работа с toString и очередью в Java

QUEUE TESTING 

3 

7 

7 

4 

The size of the queue is: 3 

The queue contains: 

4 9 8 

Но вместо этого, я получаю это:

QUEUE TESTING 
3 
7 
7 
4 
The size of the queue is: 3 
The queue contains: 
9 8 

И я не могу понять, почему четыре не возвращается с 9 и 8. Может кто-нибудь, пожалуйста, скажите мне, что происходит. Благодаря!

Вот код, я работаю с (прикрепленными файлами влево-аут):

public class Murray_A06Q1 { 

    public static void main(String[] args) { 

     LinkedQueue<Integer> queue = new LinkedQueue<Integer>(); 
     System.out.println("QUEUE TESTING"); 

     queue.enqueue(3); 
     queue.enqueue(7); 
     queue.enqueue(4); 
     System.out.println(queue.first()); 
     queue.dequeue();   
     queue.enqueue(9); 
     queue.enqueue(8); 
     System.out.println(queue.first());   
     System.out.println(queue.dequeue()); 
     System.out.println(queue.first());   

     System.out.println("The size of the queue is: " + queue.size()); 
     System.out.println("The queue contains:\n" + queue.toString());   
    } 


    public static class LinkedQueue<T> implements QueueADT<T> { 
    private int count; 
    private LinearNode<T> head, tail; //front, back 

    // Constructor  
    public LinkedQueue() { 
     count = 0; 
     head = tail = null; 
    } 

    // Adds the specified element to the tail of this queue. 
    public void enqueue(T element) { 

     LinearNode<T> node = new LinearNode<T>(element); 

     if (isEmpty()) 
      head = node; 
     else 
      tail.setNext(node); 

     tail = node; 
     count++; 
    } 

    //Removes the element at the head of this queue and returns a 
    public T dequeue() throws EmptyCollectionException { 
     if (isEmpty()) 
      throw new EmptyCollectionException("queue"); 

     T result = head.getElement(); 
     head = head.getNext(); 
     count--; 

     if (isEmpty()) 
      tail = null; 

     return result; 
    } // End of dequeue 

    // first() throws EmptyCollectionException   
    public T first() throws EmptyCollectionException { 
     return head.getElement(); 
    } 

    // Beginning of isEmpty()   
    public boolean isEmpty() { 
     if(count == 0){ 
      return true; 
     } 
     else { 
      return false;   
     } 
    } // End of isEmpty() 

    // Beginning of size()   
    public int size() { 
     return count; 
    } 

    // Begin of toString() method   
    public String toString() { 

     if (isEmpty()) { 
      return " "; 
     } 

     StringBuilder sb = new StringBuilder(); 
     LinearNode<T> next = head.getNext(); 

     while(next != null){ 
      sb.append(" ").append(next.getElement()); 
      next = next.getNext(); 
     } 
     return sb.toString(); 
    } // End of toString method 

    } 

} 
+0

Это потому, что вы начинаете с узла 'head.getNext();' вместо того, чтобы начинать с узла 'head'? – gla3dr

ответ

1

Вы должны написать свой метод ToString, как это:

public String toString() { 

    if (isEmpty()) { 
     return " "; 
    } 

    StringBuilder sb = new StringBuilder(); 
    LinearNode<T> next = head; 

    while(next != null){ 
     sb.append(" ").append(next.getElement()); 
     next = next.getNext(); 
    } 

    return sb.toString(); 

} // End of toString method 

ToString никогда не распечатывающих ГОЛОВЫ, так как вы назначили head.getNext к следующему до вашего цикла.

2

Вы начиная со вторым элементом. В toString() вы инициализируете next с head.getNext(), где head является первым и head.next() является вторым элементом. Это приводит к тому, что вывод пропускает первый элемент, и это вызовет NullPointerException, если в очереди будет ровно один элемент.

Инициализировать next до head вместо этого.

Смежные вопросы