Reputation: 985
this is my code for main class and doubly linked class and node class but when I run the program ,in the concole will show this"datastructureproject.DoublyLinkedList@19ee1ac" instead of the random numbers .please help me thanks!
main class:
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);
}
}
doubly linked list class:
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();
}
}
and the node class is like the class that you have seen before (Node prev,Node next,int value)
edited: I have added toString method but will show null pointer exception for line "result.append(temp.getValue() + " - ");" please help me thanks
Upvotes: 1
Views: 4937
Reputation: 36640
running System.out.println(Object);
will need to convert Object
into a string. It does this by executing the toString
method. If an object has not implemented toString
the default implementation is used which returns the class name and its hashcode.
you will need to either override the object and supply a suitable toString
or loop through the elements and build your string prior to calling println
yourself.
Upvotes: 0
Reputation: 1721
When you print the object, it executes it's .toString() method. What you see is the default toString implementation.
You can override .toString to customize what get's printed - in your case, you'd probably loop over the items and create a comma-separated list of the numbers or something
Upvotes: 1
Reputation: 16230
When you call System.out.println
on an object it (kindly) calls the toString
method of that object. If you haven't defined a toString
for an object you will get the one defined by one of it's ancestors. In your case you aren't extending anything, so you will get the toString of Object
- probably not what you want.
Try defining a toString() method in your class. In it you should probably loop over the nodes and build a String
containing the required representation.
Upvotes: 2