-1

I'm trying to randomly select an element from a 2-d array. I specifically only one element e.g. x1

public static void main(String[] args) {
    Random rand = new Random();
    String[][] couples = {{"x1","y1"},{"x2","y2"},{"x3","y3"},{"x4","y4"},{"x5","y5"}};
    int rnd=rand.nextInt(couples.length);
    System.out.println(couples[rnd]);
}

This is what I've got so far but it prints out: [Ljava.lang.String;@4517d9a3

M.Huss
  • 9

3 Answers3

1
public static void main(String[] args) {
    Random rand = new Random();
    String[][] couples = {{"x1","y1"},{"x2","y2"},{"x3","y3"},{"x4","y4"},{"x5","y5"}};
    int rnd1 = rand.nextInt(couples.length);
    int rnd2 = rand.nextInt(couples[rnd1].length);
    System.out.println(couples[rnd1][rnd2]);
}
Silird
  • 176
  • 1
  • 11
0

Here you are only specifying random number for the element of first array. Since the element in first array is another array that contains two elements, you have to specify another random number to pick a one like below,

  public static void main(String[] args)
  {
    Random rand = new Random();
    String[][] couples = { { "x1", "y1" }, { "x2", "y2" }, { "x3", "y3" }, { "x4", "y4" }, { "x5", "y5" } };
    int rndOne = rand.nextInt(couples.length);
    int rndTwo = rand.nextInt(couples[rndOne].length);
    System.out.println(couples[rndOne][rndTwo]);
  }
Sandeepa
  • 3,457
  • 5
  • 25
  • 41
0

System.out.println(couples[rnd])

gives you

[Ljava.lang.String;@4517d9a3

This means your object is a String[]

Remember couples is a String[][]; a 2D array, so giving one index returns you another String[], not a single String.

You need to select another index from the String[]

Something like

int rnd=rand.nextInt(couples.length);
int rnd2 = rand.nextInt(couples[rnd]);
System.out.println(couples[rnd][rnd2]);

Additionally, have a look at https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getName to understand why you get [Ljava.lang.String;@4517d9a3.

user1717259
  • 2,717
  • 6
  • 30
  • 44