0

I want to make an application where I take a number, which is the ammount of boxes, create an array and then fill out the array with the height of boxes and then print out all the boxes in the array with their height.

public class Boxes {
    static class Box {
        int height; 

        Box(int h) {
            this.height = h;
        }
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        Box arr[] = new Box[n];

        for (int i = 0; i < n; i++) {
            int h = s.nextInt();
            arr[i] = new Box(h);
        }

        System.out.println(Arrays.toString(arr));
    }
}

When I enter 3 5 3 2 I want it to print out 5,3,2, but it prints out a memory address.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • How should Java know that the string representation of a `Box` is the value of its `height` field? Hint: it doesn't. Write a `toString()` method in your `Box` that returns something like `String.valueOf(this.height)`. – Joachim Sauer Jan 15 '19 at 09:49
  • why dont you iterate your resultant array(`arr`) through a loop?? `for(Box bb: arr) { System.out.println(bb); } ` – Vishwa Ratna Jan 15 '19 at 09:55

2 Answers2

1

You have to override the toString() method in your Box class:

class Box {
     private final int height;

     public Box(int h){
         height = h;
     }

     @Override
     public String toString(){
         return Integer.toString(height);
     }
}

As the default implementation is inherited by the Object class (the base class to every object in java), which looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Note that it's not printing the memory address but rather a hexadecimal representation of the hashcode returned by the hashcode()-method

Lino
  • 19,604
  • 6
  • 47
  • 65
0

Arrays.toString loops each element in the array, loop and invoke String.valueOf(element) for each element, and append them into a StringBuilder result.

String.valueOf(Box box) actually invokes box.toString(), since Box class does not Override method toString(), then parent class Object.toString() will be invoked and className@HexString(hashCode()) will be returned.

you can either override toString() method in Box, to return String value of height ([5, 3, 2] will be printed), or loop and print height of each Box in the array.

Sandy W
  • 1
  • 1