user3124181
user3124181

Reputation: 863

Refer To Arrays Dynamically Java

I have a series of arrays in my Java program

Integer[] row1 = {0,0,0,0,0,0};
Integer[] row2 = {0,0,0,0,0,0};
Integer[] row3 = {0,0,0,0,0,0};
Integer[] row4 = {0,0,0,0,0,0};
Integer[] row5 = {0,0,0,0,0,0};
Integer[] row6 = {0,0,0,0,0,0};

I also have a randomly generated number between 1-6:

    int selectrow = rand.nextInt(6)+1;

I need to refer to each of those rows based on the value of the generated number. So something like "row" + selectrow and then do something to it, but I am not sure how to achieve this without if statements. If statements would just get too messy. Any ideas?

Upvotes: 0

Views: 69

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382112

Build an array of arrays.

And use int, not Integer, unless you have a very specific reason for using expensive objects.

And use loops to fill your matrix. Unless you fill it with 0 and use int, because, well, it's the default value.

All in one, here's what your code could be like:

    int[][] matrix = new int[6][6];
    Random rand = new Random();
    // there's probably something happening here
    int[] selectedRow = matrix[rand.nextInt(6)];

Upvotes: 1

folkol
folkol

Reputation: 4883

Add them to an array of arrays:

Integer[][] arrays = { row1, row2, row3, row4, row5, row6 };
Integer[] row = arrays[selectRow];

Upvotes: 0

DarkDust
DarkDust

Reputation: 92326

Instead of using separate variables for each row, you're almost always better off using a two-dimensional array instead. Selecting a new row is trivial then:

Integer[] row = rows[rand.nextInt(6)];

(Note that indices start at 0, not 1.)

Upvotes: 0

Seelenvirtuose
Seelenvirtuose

Reputation: 20608

You should work with an array of arrays:

Integer[][] rows = createRows();
int selectrow = rand.nextInt(6);
Integer[] = rows[selectrow];

Note that I removed the +1 part in the initialization of variable selectrow. Arrays in Java have 0-based indexes.

Upvotes: 0

Related Questions