-1

I have a rather simple incomplete program involving nodes. I haven't gotten too far, but I'm having an issue. I've created a node and it's a string type. But when running the program, instead of printing the defined string, the output is the node name, followed by "@" and a bunch of letters and digits.

import java.util.Scanner;

public class Node {
   public static void main (String[] args) {

   Node x = new Node("ABCDEFG",null);
   System.out.print(x);

}//void main

private String data;
private Node next;

public Node(String d, Node nx) {
    data = d;
    next = nx;
}

public String getData() {return data;}

public Node getNext() {return next;}

public void setData(String d) {data = d;}

public void setNext(Node n) {next = n;}

}// Node class

However the output is not shown as defined at the top, but looks like this:

Node@6d06d69c

Any possible solutions?

craigcaulfield
  • 3,381
  • 10
  • 32
  • 40
Mr. O
  • 1

2 Answers2

0

Node@6d06d69c is the representation of the object x which is of type Node. To print the actual string value you are passing in constructor, you either need to call getData() method or override toString() in Node class to return data .

Smile
  • 3,832
  • 3
  • 25
  • 39
0

First and foremost, you need to understand toString in java.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

So make sure you print what you intend to print, you have to @Override the toString() automatically implicitly inherited from the Object.

Here is a demo for this in your case:

public class NodeToString {
    static class Node {
        int val;
        Node next;
        public Node(int theVal, Node theNext) {
            this.val = theVal;
            this.next = theNext;
        }

        @Override
        public String toString() {
            return String.format("{value: %d, hasNext: %s}", this.val, this.next != null);
        }
    }

    public static void main(String... args) {
        Node head = new Node(1, null);
        System.out.println(head);
    }
}

And the output:

{value: 1, hasNext: false}
Hearen
  • 7,420
  • 4
  • 53
  • 63