简体   繁体   中英

How can I initialize an 2D array with 1D array?

I just want to initialize a 2D array with 1D array values which is in a loop... like

for (int i=0; i<=x ; i++){  // x will be taken by user input(Scanner)
   for (int j=0; j<=3; j++){

     char s[][] = new char[x][6];
     System.out.println("Enter value a : ");
     a = input.nextInt();

     if (a==1){
        char r[] = {'A','B','C','D','E','F'};
        s[i][j] = r ;  // **Here is where I'm stuck at...**
     }
     else if (a==2){
       char r[] = {'G','H','I','J','K','L'};
       s[i][j] = r ;  // **Here is where I'm stuck at...**
     }
   }
}

I want my final 2D array as below for following the inputs x=2 a=1,a=2 &a=1

s[][]={{'A','B','C','D','E','F'},{'G','H','I','J','K','L'},{'A','B','C','D','E','F'}};

Please correct me If I was asking impossible one... Or provide me another method to get such result.... Thank you

Change:

s[i][j] = r ;

to:

s[i] = r ;

Hopefully that should work.

s[i][j] is asking for a specified char in the 2D char array(because you're giving both dimensions, i being y and j being x). s[i] returns an entire row as an array. Since, you were looking to set row i to {'A', 'B', 'C', 'D', 'E', 'F'} , you should use s[i] .

You could accomplish want you want by using a jagged array:

char[][] s = new char[6][];

for (int i=0; i < 6; ++i) {
    int a = input.nextInt();

    if (a == 1) {
        s[i] = {'A','B','C','D','E','F'};
    }
    else if (a == 2) {
        s[i] = {'G','H','I','J','K','L'};
    }
}

It seemed that the spirit of what you were trying to do was to initialize a 2D array using 1D arrays in a loop. The above code snippet does that, using static 1D array initialization.

Here are some code examples to get you going:

char[][] matrix = new char[2][4];
for (int i=0; i < 2; i++) {
  // now create an array for the columns
  matrix[i]= new char[4];
  // now you could do
  for (int j=0; j < 4; j++) {
    matrix[i][j] = ...
  }
  // or
  char[] row = { '1', '2', '3', '4' };
  matrix[i] = row;
}

The idea is that you first say how many rows and columns you have. Then you iterate the first dimension, and you can set the values for the second dimension during each iteration. You can either set each cell using x/y coordinates; or you populate a whole row in one shot.

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