我目前正在使用Java 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 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但如果我擺脫靜態關鍵字一些方法顯示錯誤給我。 – Acetamide
確保所有的靜態關鍵字都不見了,也就是方法聲明中的那些... –