简体   繁体   English

如何使用1D数组初始化2D数组?

[英]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 我只想使用循环中的1D数组值初始化2D数组...

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 我希望我的最终2D数组如下所示以跟随输入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][j]在2D char数组中请求指定的char(因为您同时给出了两个维度,i为y,j为x)。 s[i] returns an entire row as an array. s[i]返回整行作为数组。 Since, you were looking to set row i to {'A', 'B', 'C', 'D', 'E', 'F'} , you should use s[i] . 由于您希望将第i行设置为{'A', 'B', 'C', 'D', 'E', 'F'} ,因此应使用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. 看来,您尝试做的精神是在循环中使用1D数组初始化2D数组。 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; 您可以使用x / y坐标设置每个单元格 or you populate a whole row in one shot. 或您一口气填满整

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM