0

I have tried many different things to try to print this stack but it keeps printing the hashcode ie. Problem1$Node@3d4eac69. I have searched a lot online and found nothing that has worked for this so if there are any suggestions help is greatly appreciated.

import java.util.*;

public class Problem1 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    // Reading the first integer containing the number of test queries
    int N = input.nextInt();
    // Initializing the maximum value
    int max = Integer.MIN_VALUE;
    // Initializing the stack. 
    Stack<Node> stack = new Stack<Node>();
    // Read the query and perform the actions specified. 
     for(int i = 0; i < N; i++){
         int x = input.nextInt();
        if(x == 1){
            int value = input.nextInt();
            Node n = new Node(value);
           stack.push(n);
           System.out.println(stack);
        }
        else if(x == 2){
           stack.pop();
        }
        else if(x == 3){
           System.out.println(stack.peek());
        }
     }
    }

static class Node{
    int data;

    public Node(int data){
        this.data = data;
    }
}    

}
Aaron
  • 3
  • 1

1 Answers1

2

You need to override the default toString method (inherited from Object see API here ) in your Node class, something like this:

static class Node {
    int data;

    public Node(int data){
        this.data = data;
    }

    @Override
    public String toString() {
      return "Node: "+data;
    }

}    

The toString method is used when you try to print the object as a String. If you don't have one, it will use the Object's one which builds a String this way

getClass().getName() + '@' + Integer.toHexString(hashCode()))

and gives you something like Problem1$Node@3d4eac69

Bentaye
  • 9,403
  • 5
  • 32
  • 45