我目前正在使用Java GUI在链接列表中执行图书清单系统。我必须将书籍信息添加到链接列表中的节点,并通过实现迭代器来显示它。为什么我的链接列表中的数据不会显示? Java
练习要求我使用自己的链接列表,然后实现迭代器以仅显示它。
我已经完成了我的代码,它显示没有错误。但是,当我运行GUI并成功将书籍添加到链接列表中时,请按下显示按钮。它没有显示我刚添加到文本区域的信息。
代码中出现了什么问题?
这是我的Node类:
public class Node
{
Data data;
Node next;
public Node()
{
next = null;
}
Node(Data data, Node next)
{
this.data = data;
this.next = next;
}
public Object getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next=next;
}
}
这是我的LinkedList类与插入和显示方法:
public class LinkedList
{
Node node = new Node();
static Data data;
static Node head;
public LinkedList()
{
head=null;
}
public static Node getHead()
{
return head;
}
public static void addNode(Data data, Node head)
{
Node newNode = new Node(data, head);
Node previous = null;
Node current = head;
while(current != null && data.name.compareTo(current.data.name) >= 0){
previous = current;
current = current.next;
}
if(previous == null){
head = newNode;
}else{
previous.next = newNode;
}
newNode.next = current;
JOptionPane.showMessageDialog(null,"Book Information has been added to the inventory.");
}
}
public static String displayNode()
{
DisplayIterator i;
Node current = head;
String output = "";
while(DisplayIterator.hasNext())
{
output+= DisplayIterator.next();
current=current.next;
}
return output+"NULL";
}
这是我用于存储所有的信息我的数据类到一个节点:
public class Data {
String name;
String author;
int isbn;
int number;
String genre;
LinkedList list;
static Node head = LinkedList.getHead();
public Data(String name, String author, int isbn, int number, String genre)
{
this.name = name;
this.author = author;
this.isbn = isbn;
this.number = number;
this.genre = genre;
}
public String toString(String name, String author, int isbn, int number, String genre)
{
return("Book Name: "+name+"\nAuthor: "+author+"\nISBN Number: "+isbn+"\nNumber of Copies: "+number+"\nGenre: "+genre+"\n");
}
}
public String getName()
{
return name;
}
public static Node getHead()
{
return head;
}
最后一点,这是我的迭代器类:
public class DisplayIterator
{
Data data;
static Node current;
DisplayIterator(Data data)
{
this.data = data;
current = data.getHead();
}
public static boolean hasNext()
{
if(current != null){
return true;
}
return false;
}
public static Object next()
{
if(hasNext()){
current = current.getNext();
return current.getData().toString();
}
return null;
}
public void remove()
{
throw new UnsupportedOperationException("It is read-only.");
}
}
当我运行GUI时,在插入之后,我单击按钮以显示文本区域中的链接列表,但是没有任何内容出现在那里。为什么?
这是我的显示按钮
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
LinkedList list;
jTextArea1.setText(LinkedList.displayNode());
}
请帮忙告诉我什么是错的代码。谢谢。
你把静态和实例方法和变量混淆在你的代码中。尝试摆脱静态。这里你不需要它。 –
@YaroslavRudykh但如果我摆脱静态关键字一些方法显示错误给我。 – Acetamide
确保所有的静态关键字都不见了,也就是方法声明中的那些... –