S. Anthony S. Anthony - 2 months ago 8
Java Question

Array doesn't print content

I am trying to print array's content with

toString()


and I can't figure out what I am doing wrong.

The output should be 5 random numbers from 0 to 100 which I will store in array after all I have to print them all.

Here is my code:

public class Ary {

private int[] anArray;
private int arraySize;
private String numberAsString;
Random r = new Random();

public Ary(int arraySize) {
this.anArray = printArray();
}

public Ary() {
arraySize = 2;
printArray();
}

public int getArraySize() {
return arraySize;
}

public void setArraySize(int arraySize) {
this.arraySize = arraySize;
}

public int[] printArray() {
// Assign anArray with a custom number
anArray = new int[arraySize];

for(int numbers : anArray) {
anArray[numbers] = r.nextInt(100);
System.out.println(anArray[numbers] + " ");
}
return anArray;
}

@Override
public String toString() {
return "Array = " + Arrays.toString(anArray);
}
}


Output:

Music.app.Ary@5e2de80c


Here is my code with Arrays.toString():

public int[] printArray() {
// Assign anArray with a custom number
anArray = new int[arraySize];

for(int numbers : anArray) {
anArray[numbers] = r.nextInt(100);
System.out.println(Arrays.toString(anArray));
}
return anArray;
}


I've already tried tons of methods but still haven't figure it out.. Can you please explain what am I doing wrong?

Thank you very much!

Answer

You've changed the signature of toString() (so you aren't calling the method you have defined). Instead, you need something like1,

@Override
public String toString() {
    return "Array = " + Arrays.toString(anArray);
}

And you should probably initialize anArray in your constructor(s)2 and remove "printArray"

public Ary(int arraySize) {
    this.arraySize = arraySize;
    this.anArray = new int[arraySize];
    for (int i = 0; i < arraySize; i++) {
        this.anArray[i] = r.nextInt(101); // <-- [0, 100], or [0, 101)
    }
}

public Ary() {
    this(5); // <-- use the other constructor.
}

1And the override annotation will alert you to this mistake.
2And you shouldn't print the array until you finish initializing it.

Comments