我正在创建一个使用 GUI 形式的链接列表存储数据的系统。 我在存储和显示链接列表时遇到了一些问题。貌似我输入数据后,并没有存入链表
我正在做的是一个图书馆系统,所以我需要的是将书名、作者姓名、ISBN号和书本的份数存储到链表中的单个节点中。这些信息来自用户输入,例如 jTextField1。我的讲师教我如何插入单个数据,但现在我需要插入多个数据。
我在 Node 类中重新创建了构造函数和 getter 方法,并在 LinkedList 类中对其进行了更改。但由于某种原因,数据似乎没有添加到 LinkedList 中,当我在 TextArea 中显示列表时,它显示的所有内容都是 NULL,而不是我刚刚输入的数据。这是为什么?
这是我的 Node 类:
public class Node
{
String name;
String author;
int isbn;
int number;
Node next;
Node()
{
name = null;
author = null;
isbn = 0;
number = 0;
next = null;
}
Node(String name, String author, int isbn, int number)
{
this.name = name;
this.author = author;
this.isbn = isbn;
this.number = number;
}
String getName()
{
return name;
}
String getAuthor()
{
return author;
}
int getisbn()
{
return isbn;
}
int getnumber()
{
return number;
}
Node getNext()
{
return next;
}
void setNext(Node next)
{
this.next=next;
}
}
这是我的链接列表类:
public class LinkedList
{
Node node = new Node();
Node head;
LinkedList()
{
head=null;
}
Node getHead()
{
return head;
}
public void addNode(String name, String author, int isbn, int number)
{
Node newNode = new Node(name, author, isbn, number);
newNode.next = head;
head = newNode;
JOptionPane.showMessageDialog(null,"Node added to the list.");
}
}
public String displayNode()
{
Node current = head;
String output = "";
while(current!= null)
{
output+="Book Name: "+current.getName()+" Author: "+current.getAuthor()+" ISBN Number: "+current.getisbn()+" Number of copies: "+current.getnumber();
current=current.getNext();
}
return(output+"NULL");
}
这就是我的 AddBook JFrame 中的内容:
public class AddBook extends javax.swing.JFrame {
static String name;
static String author;
static int isbn;
static int number;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
LinkedList list = new LinkedList();
list.addNode(jTextField2.getText(), jTextField3.getText(), Integer.parseInt(jTextField4.getText()), Integer.parseInt(jTextField1.getText()));
}
}
另一个带显示的 JFrame:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
LinkedList list = new LinkedList();
jTextArea1.setText(list.displayNode());
}
数据类:
public class Data {
String name;
String author;
int isbn;
int number;
public Data(String name, String author, int isbn, int number)
{
}
}
有人可以帮我解决这个问题吗?谢谢。
最佳答案
将节点想象成一个可以包含任何数据的存储桶,而不仅仅是简单的数字(正如大多数教程所描述的那样)。
而不是 int num
您的 Node
中的字段类,您可以使用任何您想要的引用类型,例如 List<Integer>
:
public class Node {
List<Integer> data;
...
}
在这种情况下,您还需要重写构造函数和 getter(通过分别更改参数类型和返回类型)。
另一个不会破坏的好解决方案 the single responsibility principle将使用包装类(例如 Data
):
class Data {
private Integer i;
private String s;
}
关于java - 数据未添加到链表并正确显示。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40574361/