简单地说,我希望我的代码将给定的元素添加到列表中,并将其打印到屏幕上。问题是,它打印列表的最后一个元素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;
}
}
这是节点类:
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;
}
}
}
您的节点类还需要一个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;
}
我已经测试过了,它是有效的。
希望这能有所帮助,
利亚姆
使用三个不同的Book,而不是仅使用一个bk1
。