【发布时间】:2016-11-18 14:21:13
【问题描述】:
我目前正在使用 Java GUI 在链表中创建图书库存系统。我必须将书籍信息添加到链表中的节点中,并通过实现迭代器来显示它。
练习要求我使用自己的链接列表,然后实现迭代器以仅显示它。
我已经完成了我的代码,它没有显示错误。但是,当我运行 GUI 并成功将一本书添加到链接列表中时,然后按显示按钮。它没有显示我刚刚添加到文本区域的信息。
代码中的哪些地方做错了?
这是我的节点类:
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 但是如果我去掉 static 关键字,某些方法会向我显示错误。
-
确保所有静态关键字都消失了,还有方法声明中的关键字...
-
@AdriaanKoster 好的,我试试看,是不是 TextArea 中没有显示信息的问题?
-
可能是这样。您的程序流程因此而模棱两可。
标签: java linked-list iterator