0

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?

user3124181
  • 782
  • 9
  • 24

4 Answers4

1

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)];
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

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.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

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.)

Community
  • 1
  • 1
DarkDust
  • 90,870
  • 19
  • 190
  • 224
0

Add them to an array of arrays:

Integer[][] arrays = { row1, row2, row3, row4, row5, row6 };
Integer[] row = arrays[selectRow];
folkol
  • 4,752
  • 22
  • 25