1

I want to use the elements of array comNumber, in ranNumber() method but when I using this in main() it only shows the address of array. How can I fix this problem?

public class BaseballGame {
    public static void main(String[] args) {
        BaseballGame bGame = new BaseballGame();
        System.out.println(bGame.ranNumber());


    }

    public int[] ranNumber() {
        Random rand = new Random();
        int[] comNumber = new int[3];
        for(int i=0; i<comNumber.length; i++) {
            comNumber[i] = rand.nextInt(10);
            for(int j=0; j<i; j++) {
                if (comNumber[i] == comNumber[j]) {
                    i--;
                    break;
                }
            }
        }
        return comNumber;
    }
}
Rohan Pillai
  • 917
  • 3
  • 17
  • 26
godlovesjoe
  • 43
  • 1
  • 3

2 Answers2

1

If you want to use it just don't print it.

int[] result  = bGame.ranNumber();

Use result now in your main method.

If you want to see what is returned,

System.out.println(Arrays.toString(result));

public static void main(String[] args) {
    BaseballGame bGame = new BaseballGame();
    int[] result  = bGame.ranNumber();
    System.out.println(Arrays.toString(result));
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

bGame.ranNumber() will return an int[], and arrays are objects in java. So Calling System.out.println(bGame.ranNumber()) will call the toString method of array under the hood. The default implementation of toString in class Object will print that address. That's the reason you get the address of that array instead of the real elements in the array.

If you want to see the real elements you should do:

int[] result = bGame.ranNumber();
for(int i=0; i < result.length; i++){
    System.out.println(result[i]);
}

or

System.out.println(java.util.Arrays.toString(result));
STaefi
  • 4,297
  • 1
  • 25
  • 43