gpt4 book ai didi

java - 添加和打印链接列表时出现错误

转载 作者:行者123 更新时间:2023-11-30 02:46:12 25 4
gpt4 key购买 nike

简单地说,我希望我的代码将给定元素添加到列表中并将其打印到屏幕上。问题是,它打印列表的最后一个元素 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;
}
}


}

最佳答案

您的节点类还需要一个 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;

}

我已经测试过这个并且它有效。

希望这有帮助,

利亚姆

关于java - 添加和打印链接列表时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40131840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com