【发布时间】:2016-11-18 09:51:29
【问题描述】:
我目前正在使用 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 Node getHead()
{
return head;
}
public static void addNode(Data data)
{
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 = null;
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;
Node head;
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 class DisplayIterator
{
Data data;
static Node current;
DisplayIterator(Data data)
{
this.data = data;
current = data.head;
}
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.");
}
}
我认为问题出在 DisplayIterator 类上,但我看不出在哪里。 谁能帮我?谢谢你。
【问题讨论】:
-
为什么要使用自己的
LinkedList和迭代器类而不是JDK 中已有的那些?你调试过你的代码吗?除此之外,您似乎在某些文本区域中显示新元素时遇到问题,但您没有提供有关如何添加元素以及如何更新文本区域的任何详细信息。 -
你在哪里实例化
DisplayIterator?此外,它的方法不应该是静态的。 -
@Thomas 这就是练习所要求的,使用我自己的链表然后实现迭代器来显示它。 add 方法在 Linked List 类中,我通过 GUI 添加它,单击 add 按钮然后它将调用 LinkedList.addNode 方法。是的,我已经调试了代码,但没有任何结果。
-
@Berger 在LinkedList类中,displayNode方法。
-
你永远不会实例化它,即你永远不会调用它的构造函数。
标签: java linked-list iterator