[英]Why the data in my linked list will not be displayed? Java
我目前正在使用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新實例。 您不要在函數內部或LinkedList構造函數內部調用`list.addNode(),因此list不包含任何數據。 如果您有LinekdList的任何其他實例包含要顯示的數據,則應使用它而不是函數內的此實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.