我目前正在使用Java GUI在鏈接列表中執行圖書清單系統。我必須將書籍信息添加到鏈接列表中的節點,並通過實現迭代器來顯示它。鏈接列表中的數據不會顯示在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 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中的類?你有沒有調試你的代碼?除此之外,您似乎在某些文本區域顯示新元素時遇到問題,但未提供有關如何添加元素以及如何更新文本區域的任何詳細信息。 – Thomas
你在哪裏實例化DisplayIterator?另外,它的方法不應該是靜態的。 – Berger
@Thomas這是練習所要求的,使用我自己的鏈表,然後實現迭代器來顯示它。 add方法位於鏈接列表類中,我通過GUI添加它,單擊添加按鈕,然後它將調用LinkedList.addNode方法。是的,我有調試代碼,但沒有出來。 – Acetamide