我在爲鏈接列表做循環時遇到了麻煩。 我想嘗試從用戶輸入ID和名稱,但似乎最後輸入的細節正在覆蓋整個鏈接的事情。但是當我使用實例(myLinkedList.insertFirstLink("name", id))
,它確實有效。鏈接列表(循環)
這裏是我的代碼..
import java.io.*;
import java.util.*;
class Example
{
public static int ID;
public static int ans;
public static String name;
public Example next;
public Example(int ID, String name)
{
this.ID = ID;
this.name = name;
}
public void display()
{
System.out.println("ID: "+ID + " - " + name);
}
public String toString()
{
return name;
}
public static void main(String args[]) throws IOException
{
BufferedReader inpt = new BufferedReader(new InputStreamReader (System.in));
int x = 0;
LinkList myLinkedList = new LinkList();
while(x<=2)
{
System.out.print("Enter Name: ");
name = inpt.readLine();
System.out.print("Input ID#: ");
ID = Integer.parseInt(inpt.readLine());
System.out.println();
myLinkedList.insertFirstLink(name, ID);
x++;
}
/* myLinkedList.insertFirstLink("Vishera", 2341);
myLinkedList.insertFirstLink("Bulldozer", 1234);
myLinkedList.insertFirstLink("Allendale", 3214);
myLinkedList.insertFirstLink("Wolfdale", 4312); */
myLinkedList.displayLink();
}
}
class LinkList
{
public Example head;
public Example tail;
public LinkList()
{
head = null;
tail = head;
}
public boolean isEmpty()
{
return(head == null);
}
public void insertFirstLink(String name, int ID)
{
Example newLink = new Example(ID, name);
if(head==null)
{
head = newLink;
tail = head;
}
else
{
tail.next = newLink;
tail = newLink;
}
}
public void displayLink()
{
Example theLink = head;
while(theLink != null)
{
theLink.display();
System.out.println("The Next Link: " + theLink.next);
theLink = theLink.next;
System.out.println();
}
}
}
謝謝!
調試你的代碼,你會在不到3秒發現問題。 – Maroun
爲什麼你在你的Example類中使你的字段是靜態的?讓他們成爲一個實例,它應該按預期工作。 –
@KevinBowersox每個'Example'對象都有'next'字段。 –