这是我对主类和双向链接类和节点类的代码,但是当我运行该程序时,在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