Aro
Aro

Reputation: 494

Java - Is there a way to call a variable using a variable as part of its name?

This is what I'm doing,

for (i=0; i<4; i++){
    for (j=0; j<7; j++){
        someArray[1][i][j] = value1[i][j];
    }
}
for (i=0; i<4; i++){
    for (j=0; j=0; j<7; j++){
        someArray[2][i][j] = value2[i][j];
    }
}

This is what I'd like to do

for (j=0; j<14; j++){
    for (i=0; i<4; i++){
        for (j=0; j=0; j<7; j++){
            someArray[j][i][j] = value%j%;
        }
    }
}

Is there a way to do something like this?

The reason I am doing this is because I need to set the value of an array and I don't know how to declare values for multidimensional string arrays.

I know how to do this

public static String value1[] = {
    "somevalue",
    "morevalue",
    "blahvalue"
};

but I don't know how to do that if I'm declaring...

public static String value[][] = ...

Upvotes: 2

Views: 75

Answers (2)

Federico Builes
Federico Builes

Reputation: 5097

I'm not sure how to do exactly what you wanted, but you can always store the different values in an array and then loop over them doing something like this:

int x =  3; // number of values
SomeType[] values = new SomeType[x];
values[0] = value1;
values[1] = value2;
values[2] = value3;

for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 7; j++) {
        for (int k=0; k < x; k++) {
            someArray[k][i][j] = values[k][i][j];
        }
    }
}

Upvotes: 1

Jacob
Jacob

Reputation: 78850

It is very complicated and not recommended to reference variables with a dynamic name. To initialize a multi-dimensional Java array, do this:

public static String[][] someArray = {
    {"A", "B", "C", "D"},
    {"E", "F", "G", "H"},
    {"I", "J", "K", "L"}
};

Upvotes: 4

Related Questions