這是我對主類和雙向鏈接類和節點類的代碼,但是當我運行該程序時,在concole中將顯示此「[email protected]」而不是隨機數。請幫助我謝謝!將元素添加到雙向鏈表中
主類:
public class Main {
public static int getRandomNumber(double min, double max) {
Random random = new Random();
return (int) (random.nextDouble() * (max - min) + min);
}
public static void main(String[] args) {
int j;
int i = 0;
i = getRandomNumber(10, 10000);
DoublyLinkedList listOne = new DoublyLinkedList();
for (j = 0; j <= i/2; j++) {
listOne.add(getRandomNumber(10, 10000));
}
System.out.println(listOne);
}
}
雙向鏈表類:
public class DoublyLinkedList {
private Node head ;
private Node tail;
private long size = 0;
public DoublyLinkedList() {
head= new Node(0, null, null);
tail = new Node(0, head, null);
}
public void add(int i){
head.setValue(i);
Node newNode = new Node();
head.setNext(newNode);
newNode.setPrev(head);
newNode = head;
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("(head) - ");
Node temp = head;
while (temp.getNext() != tail) {
temp = temp.getNext();
result.append(temp.getValue() + " - ");
}
result.append("(tail)");
return result.toString();
}
}
和節點類是像你以前(節點分組,節點接下來,int值)看到的類
編輯:我添加了toString方法,但會顯示行「result.append(temp.getValue()+」 - 「」;「)的空指針異常」請幫助我,謝謝
嗨我已經習慣了字符串方法 但現在它會顯示一個異常空指針異常 – user329820 2010-05-30 08:51:44
當你嘗試用空對象做某事時會觸發該異常。我最好的猜測是add方法不正確,'temp'在某個點變成'null',而不是變成'tail' – nc3b 2010-05-30 09:22:59