2016-10-19 22 views
1

簡単に言えば、私のコードでは、指定された要素をリストに追加して画面に出力します。問題は、リストの最後の要素を3回印刷し、他の要素を印刷しないことです。私はずいぶん過ごしましたが、問題を見つけることができませんでした。ここでリンクされたリストの追加と印刷によるエラーの取得

public class Book { 

private String name; 
private double price; 
private String writer; 

public Book(String name, double price, String writer) { 
    super(); 
    this.name = name; 
    this.price = price; 
    this.writer = writer; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public double getPrice() { 
    return price; 
} 
public void setPrice(double price) { 
    this.price = price; 
} 
public String getWriter() { 
    return writer; 
} 
public void setWriter(String writer) { 
    this.writer = writer; 
} 
} 

Nodeクラスです:

public class Node { 

public static void main(String[] args) { 

    Node nd = new Node(bk); 
    Book bk1; 
    bk1 = new Book("Of Mice and Men", 22, "John Steinbeck"); 
    nd.add(bk1); 

    bk1 = new Book("The Grapes of Wrath", 28, "John Steinbeck"); 
    nd.add(bk1); 

    bk1 = new Book("Tortilla Flat", 33, "John Steinbeck"); 
    nd.add(bk1); 

    nd.printData(); 

} 

private static Book bk; 
private Node link; 
public Node root; 


public Book getBk() { 
    return bk; 
} 
public void setBk(Book bk) { 
    this.bk = bk; 
} 
public Node getLink() { 
    return link; 
} 
public void setMyNode(Node link) { 
    this.link = link; 
} 

public Node(Book bk) { 
    super(); 
    this.bk = bk; 
    this.link=null; 
    this.root=null; 

} 

public void add(Book bk) { 
    Node currentNode = root; 
    Node newNode = new Node(bk); 
    if(root==null){ 

     root = newNode; 
    } 
    else{ 
    while(currentNode.link!=null){ 

     currentNode = currentNode.link; 

    } 
    currentNode.link = newNode; 
} 
} 

public void printData() { 
    Node currentNode = root; 

    while(currentNode!=null){ 
     Book bk = currentNode.getBk(); 
     System.out.println("Name: " + bk.getName() + " Price: " + bk.getPrice() + " Writer: " + bk.getWriter()); 
     currentNode =currentNode.link; 
    } 
} 


} 
+0

はあなたのコードをフォーマットしてもらえますか?コードを強調表示してCtrl + Kを押すと、質問に簡単に答えることができます。 –

+0

ここでノードクラスのbkの値は何ですか? 'Node nd = new Node(bk);' –

答えて

2

あなたのノードクラスもBookインスタンス変数を必要とします:

private static Book bk; 
private Book book; 
private Node link; 
public Node root; 

次に、これらのメソッドは、クラス変数の上にインスタンス変数を使用するように更新が必要です。

public Book getBk() { 
    return book; 
} 
public void setBk(Book bk) { 
    this.book = bk; 
} 
public Node(Book bk) { 
    super(); 
    this.book = bk; 
    this.link=null; 
    this.root=null; 

} 

私はこれをテストしてきたし、それが動作します。このことができます

希望、

リアム

+1

を正確に変更しなかったことを試しました。それは質問者にコメントしましたが、まだ応答はありません... –

0

利用代わりに一つだけbk1の三つの異なるブック。

+0

私はそれが問題 – afellay

関連する問題