简体   繁体   中英

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?

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)];

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.

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

Add them to an array of arrays:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM