2016-11-03 9 views
0

私のコードを以下に示します。&私のコードで何が問題なのかわかりません。ノードでJavaで自分自身のキューを構築する

NodeFNクラス:

public class NodeFN { 
    private String data; // Data for node. 
    private NodeFN next; // Next node. 

public NodeFN(String data) { 
    this.data = data; // Take the data value passed in & store it in the data field. 
    this.next = null; // Take the next node & store it in the next field. 
} 

// Mutator functions. 
public String getData() {return data;} 
public NodeFN getNext() {return next;} 
public void setData(String d) {data = d;} 
public void setNext(NodeFN n) {next = n;} 
} 

キュークラス:

NodeFN nn = new NodeFN(n); 
if(nn == null) { 

これらの2行は一緒に理にかなっていけない:

public class Queue { 
    NodeFN head = null; // Head of node. 
    public String n; 

public Queue() {} // Default constructor. 

public Queue(String n) { 
    head = new NodeFN(n); // head is now an object of NodeFN which holds a string. 
} 

public void add(String n) { 
    NodeFN nn = new NodeFN(n); // nn is now an object of NodeFN which holds a string. 
     if(nn == null) { // If the new node (nn) is empty. 
      head = nn; // Then allow head to equal to the new node(nn). 
     } else { 
      // If new node (nn) alphabetically comes first compared to head 
      if(nn.getData().compareTo(head.getData()) < 0) { 
       nn.setNext(head); 
       head = nn; 
      }  
     } 
    } 

public static void main(String[] args) { 
    Queue q = new Queue(); 
    q.add("some string to test to see if it prints in console"); 

    System.out.println(q); 
    } 
} 
+2

これをデバッグするオブジェクトを印刷するのは悪いことです。デバッガを使用する方法を学ぶ必要があります。 –

+1

デバッガでの実行をシングルステップ実行し、実際に書いたコードが何を参照しているかを確認してください。あなたはなぜそれが何をするのかを理解することによって、多くのことを学びます。 – Rob

+0

デバッガはどこで入手できますか? – pellepelle

答えて

2

ここから始めましょう。 Javaでは、最初の行はではない nullを返すことが保証されています。起こりうる唯一のことは、コンストラクタが例外をスローする可能性がありますが、は決してになります。

したがって:あなたのifの "then"ブランチを取ることはありません。その後

if(nn.getData().compareTo(head.getData()) 

...のみ動作します...頭が= nullの場合!。

しかし、驚き:キュークラスの2つのコンストラクタのうち、2番目のものだけがhead =!nullになっていることを確認します。

短いストーリー:これは、NullPointerExceptionがどのように現れるかです。 あなたが、それ以上に失敗してはいけません

Queue q = new Queue(); 

Queue q = new Queue("whatever"); 

にあなたの例を変更した場合。しかしもちろん、コードはまだバグです。解決すべき重要なこと:ヘッドが初期化されていることを確認する。ヌルと比較できることを確認してください...ヌルが可能な場合には!

0

ヘッドがnullのかどうかをチェックする必要があります

if(head == null) { 
      head = nn; 
     } else { 
      ...  
     } 

を、あなたはまた、この他に条件を検討する必要があります。

if(nn.getData().compareTo(head.getData()) < 0) { 
    nn.setNext(head); 
    head = nn; 
} 
else { 
    head.setNext(nn) 
} 

最後に、あなたがQueueクラスでtoString()メソッドを実装する必要がありますが..

0

新しいノードになりますあなたはそれを作成した冗談です。

関連する問題