简体   繁体   中英

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[][] = ...

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"}
};

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

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