Ryan Barnes
Ryan Barnes

Reputation: 1

How do I autonomously switch variable names in a for statement in java?

int[] col1 = new int[4];
int[] col2 = new int[4];
int[] col3 = new int[4];
int[] col4 = new int[4];
int reduction;
int x = 1;

for(int i=1; i<=16; i++){
    if(i % 4 == 0){
        x++;
        reduction += 4;
    }
    [col(x)[(i-1)-reduction] = pool[i-1];
}

In Java how would I go about automatically altering the variable name so that I don't have to make a separate for loop for each array? I'm trying to fill 4 separate arrays with the pool array values.

Upvotes: 0

Views: 58

Answers (2)

Mjmc
Mjmc

Reputation: 1

As others have said there are a couple of syntax mistakes with your code above (starting from 1 instead of 0 mostly) but I think the most important thing to learn here is how arrays of array (also known as 2d arrays) work in java!

From what you were doing above something like this would be useful.

    int[][] cols = new int[4][4];

In Java, 2d arrays can be accessed in what is known as "row major order". This means that to access col1 for example, you would do cols[1]. To access col2 you would do cols[2] and so on.

In order to access internal elements from 2d arrays, you can think about it like a coordinate system. Because we access 2d arrays via "row major order", the x and y coordinates are sort of flipped. The "graph" would look something like this:

cols = 
[A B C],
[D E F],
[G H I];

=>
cols[0][1] = B //Row 0, Col 1
cols[1][2] = F //Row 1, Col 2

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

Use a two dimensional array. And don't try to use 1 as an initial array index; or an initial loop value.

int[][] cols = new int[4][4];
int reduction = 0;
int x = 0;

for (int i = 0; i < 16; i++) {
    if (i != 0 && i % 4 == 0) {
        x++;
        reduction += 4;
    }
    cols[x][i - reduction] = pool[i];
}

Upvotes: 7

Related Questions