Zen
Zen

Reputation: 2728

[Java]Declaring Multidimensional Array within loop

String[][] aS= new String[16][3];

String[] s0 ={"FIELD0", "FIELD1", "FIELD2"};
String[] s1 ={"FIELD0", "FIELD1", "FIELD2"};
String[] s2 ={"FIELD0", "FIELD1", "FIELD2"}; ...
String[] s15 ={"FIELD0", "FIELD1", "FIELD2"};

for(int i=0;i<aS.length;i++)
{
    for(int j=0;j<3;j++)
    {
        //error!
        aS[i][j]= s+"i"+[j];   //s0[0],s0[1]...s15[3]
    }
}

Im familiar with multidimensional arrays, im just not abot to figure out how this part can be fixed: " s+"i"+[j]; "

Edit:[error] Syntax error on token "+", Expression expected after this token

Upvotes: 0

Views: 53

Answers (3)

Ebbe M. Pedersen
Ebbe M. Pedersen

Reputation: 7488

If you want to initialize your multidimensional array you can do it like this:

String[][] aS = { {"FIELD0", "FIELD1", "FIELD2"},
                  {"FIELD0", "FIELD1", "FIELD2"}, 
                  {"FIELD0", "FIELD1", "FIELD2"},
                  ...
                  {"FIELD0", "FIELD1", "FIELD2"} };

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68915

First of all in Java you cannot create dynamic names of variables. So

aS[i][j]= s+"i"+[j];   //s0[0],s0[1]...s15[3]

is incorrect

String[][] aS= new String[16][3];

This means you can have 16 1D String arrays each of size 3 i.e 3 Strings in each array.

for(int i=0;i<aS.length;i++)
{
        aS[i]= yourArray  //s0[0],s0[1]...s15[3]
}

Here yourArray should be String[] with size 3 similar to your S0 - S15.

or you can do

for(int i=0;i<aS.length;i++)
{
    for(int j=0;j<3;j++)
    {
        aS[i][j]= "FIELD" + j;
    }
}

Upvotes: 1

Maroun
Maroun

Reputation: 95948

You can't do that in Java (and in most programming languages), it doesn't support dynamic naming.

If you want to use s0, s1 or any other array, you should write it, for example:

aS[i][j]= s0[j];

Upvotes: 1

Related Questions