我目前正在使用Java GUI在链表中做图书库存系统。我必须将图书信息添加到链表中的Node中,并通过实现迭代器显示它。
练习要求我使用自己的链表,然后实现只显示它的迭代器。
我已经完成了我的代码,它显示没有错误。但是,当我运行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;
}
最后这是我的Iterator类:
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());
}
请告诉我代码有什么问题。谢谢你!
在函数jButton1ActionPerformed中创建一个不包含任何数据的LinkedList实例。你不打电话。"list. addnode()在函数内部或在LinkedList构造函数内部,所以list不包含数据。如果您有任何其他LinekdList的实例,其中包含您想要显示的数据,您应该在函数中使用它而不是这个实例。