2013-09-28 2 views
-2

Я ищу некоторую помощь с классом, который я разработал для задания. Он добавляет оценки игр в связанный список и перечисляет их с самого высокого на самый низкий. Максимальное количество баллов - 10. Я почти работаю, но не могу понять. Я добавляю первый балл, и он работает, тогда, если я добавлю второй балл, он будет работать, только если этот счет будет выше первого. Если нет, он выбрасывает java.lang.NullPointerException. Может кто-нибудь взглянуть на мой метод insert(String name, int score) и сообщить мне, в чем проблема?Top 10 Gamers Связанный список на Java

public class GamerList { 

    /** 
    * The node class stores a list element and a reference to the next node. 
    * @author johnmckillip 
    * 
    */ 

    private class Node { 

     String name; 
     int score; 
     Node next; 

     /** 
     * Constructor. 
     * @param val The element to store in the node. 
     * @param n The reference to the successor node. 
     */ 
     Node(String val1, int val2, Node n) { 

      name = val1; 
      score = val2; 
      next = n; 
     } 

     /** 
     * Constructor. 
     * @param val The element to store in the node. 
     */ 
     Node(String val1, int val2) { 

      this(val1, val2, null); 
     } 
    } 

    private Node head; 
    private Node tail; 

    /** 
    * Constructor. 
    */ 

    public GamerList() { 

     head = null; 
     tail = null; 
    } 

    /** 
    * The isEmpty method checks to see if the list is empty. 
    * @return true if the list is empty, false otherwise. 
    */ 
    public boolean isEmpty() { 

     return head == null; 
    } 

    /** 
    * The size method returns the length of the list. 
    * @return The number of elements in the list. 
    */ 
    public int size() { 

     int count = 0; 
     Node p = head; 

     while(p != null) { 

      count++; 
      p = p.next; 
     } 

     return count; 
    } 

    public void insert(String name, int score) { 

     Node node = new Node(name, score); 

     if(isEmpty()) { 

      head = node; 
      tail = node; 
     } 

     else if(head.score <= node.score) { 

      node.next = head; 
      head = node; 
     } 

     else { 

      Node frontPtr = head.next; 
      Node backPtr = head; 

      while(frontPtr.score > node.score && frontPtr.next != null) { 

       backPtr = backPtr.next; 
       frontPtr = frontPtr.next; 
      } 

      if(frontPtr != null && frontPtr.score <= node.score) { 

       backPtr.next = node; 
       node.next = frontPtr; 
      } 

      else { 

       frontPtr.next = node; 
       tail = node; 
      } 
     } 

     if(size() > 10) { 

      Node currentPtr = head; 

      while(currentPtr.next != tail) { 

       currentPtr = currentPtr.next; 
      } 

      tail = currentPtr; 
      currentPtr.next = null; 
     } 
    } 

    public void printList() { 

     Node temp = head; 

     while(temp != null) { 

      System.out.print(temp.name + " " + temp.score + " "); 
      System.out.println(""); 
      temp = temp.next; 
     } 
    } 

} 

Вот мой класс, чтобы проверить GamerList:

общественного класса TestGamerList {

/** 
* @param args 
*/ 
public static void main(String[] args) { 


    GamerList list1 = new GamerList(); 

    list1.insert("Fry", 89); 
    list1.insert("Bender", 25); 
    list1.insert("Leela", 90); 
    list1.insert("Zoidburg", 23); 
    list1.insert("Amy", 34); 
    list1.insert("Hermes", 96); 
    list1.insert("Zapp",123); 
    list1.insert("Nibbler", 56); 
    list1.insert("Calculon", 12); 
    list1.insert("Hypnotoad", 189); 
    list1.insert("Lrrr", 5); 
    list1.insert("Scruffy", 28); 

    System.out.println("Top 10 Scores: "); 
    list1.printList(); 
} 

}

+0

Java 6? Или Java 7? Что такое класс 'GamerList'? – Ilya

+0

Где методы GamersList insert и printList? Можете ли вы добавить трассировку стека? –

+2

Вы пытались настроить контрольные точки в своем коде, где вы добавляете элементы в свой список, и запускаете программу с помощью отладчика? Это покажет вам проблему в считанные секунды. – Izmaki

ответ

2

Похоже, вы не установили head «s next. Это одна проблема. Во-вторых, даже если вы это сделаете, вы попадете в бесконечный цикл, потому что вы неправильно ввели логику вставки. Я немного изменил вам insert(), чтобы заставить его работать, но ему все еще не хватает элегантности и далека от эффективной реализации. Например, при каждой вставке после того, как у вас есть 10 элементов, вы используете size(), что увеличивает сложность кода в приблизительно прибл. N = size(). Если вы действительно этого хотите, сделайте size переменной и просто увеличьте ее в конце каждого insert(). Anyway, Код редактирования:

public class GamerList { 

    private class Node { 

     String name; 
     int score; 
     Node next; 

     Node(String val1, int val2, Node n) { 

      name = val1; 
      score = val2; 
      next = n; 
     } 

     Node(String val1, int val2) { 

      this(val1, val2, null); 
     } 
    } 

    private Node head; 
    private Node tail; 

    /** 
    * Constructor. 
    */ 

    public GamerList() { 

     head = null; 
     tail = null; 
    } 

    /** 
    * The isEmpty method checks to see if the list is empty. 
    * @return true if the list is empty, false otherwise. 
    */ 
    public boolean isEmpty() { 

     return head == null; 
    } 

    /** 
    * The size method returns the length of the list. 
    * @return The number of elements in the list. 
    */ 
    public int size() { 

     int count = 0; 
     Node p = head; 

     while(p != null) { 

      count++; 
      p = p.next; 
     } 

     return count; 
    } 

    public void insert(String name, int score) { 

     Node node = new Node(name, score); 

     if(isEmpty()) { 

      head = node; 
      head.next = tail; 
     } 
     else if(head.score <= node.score) { 

      node.next = head; 
      head = node; 
     } 

     else { 
      Node beforeNode = head; 
      while(beforeNode.score > node.score && beforeNode.next != null) { 
       beforeNode = beforeNode.next; 
      } 
      node.next = beforeNode.next; 
      beforeNode.next = node; 
     } 

     if(size() > 10) { 

      Node currentPtr = head; 

      for (int i = 0; i < 9; i++) { 
       currentPtr = currentPtr.next; 
      } 
      currentPtr.next = null; 
     } 
    } 

    public void printList() { 

     Node temp = head; 

     while(temp != null) { 

      System.out.print(temp.name + " " + temp.score + " "); 
      System.out.println(""); 
      temp = temp.next; 
     } 
    } 

} 
+0

Извините, если я не был предельно ясен по тому, что я просил. Это было именно то, чего я не мог понять. Спасибо за вашу помощь! Я также изменил размер на переменную вместо вызова метода size() каждый раз, как вы предлагали. – user2827001

+0

@ user2827001, я предлагаю вам 1) прочитать что-то об основах отладки (возможно, в ваших документах IDE) и 2) прочитать что-то о структурах данных и алгоритмах (возможно, для начинающих - не начинайте с Cormen или Sedgewick;)). Удачи с этим! – tkroman

-1

без трассировки стека является сложным. , но, вероятно, ошибка здесь

while(frontPtr.score > node.score && frontPtr.next != null) 

так frontPtr равна нулю.

добавить проверку на

if (frontPtr!=null) 
    while(frontPtr.score > node.score && frontPtr.next != null) 
+0

Как это иначе? –

+0

Это пороговое значение вызывает то же исключение с изменением выше. – user2827001

+0

yep, мой плохой. Я читал это неправильно. – EsseTi

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