Java中的循环2维数组

时间:2020-12-06 21:36:52

I want to be able loop this 2 dimensional array and return the size of the first list.

我希望能够循环这个二维数组并返回第一个列表的大小。

For example:

double[][] array= {
        {  15.0, 12.0},
        {  11.0,  16.0},
        { 16.0, 12.0},
        { 11.0, 15.0},
    };

I am thinking along the lines of using a loop within a loop structure like....

我正在考虑在循环结构中使用循环,如....

for(int i=0; i < array.length; i++) {
        for(int j=0; j < array.length; j++)
        {
            //
        }

    }

Any help would be great. Thanks.

任何帮助都会很棒。谢谢。

3 个解决方案

#1


2  

Your inner for loop should check the length of the inner array

你的内部for循环应该检查内部数组的长度

for(int i=0; i < array.length; i++) {
        for(int j=0; j < array[i].length; j++) {
            //
        }
}

Or use foreach

或者使用foreach

for(double[] row : array) {
  for(double cell : row) {
     // 
  }
}

#2


0  

To get the size of the first dimension you don't need loop , just make this

要获得第一个维度的大小,您不需要循环,只需这样做

 int len = array.length/// the length of the first list

but if you want to get the size of the second dimension , and the array not empty so get the length of the first element , like this :

但是如果你想获得第二个维度的大小,并且数组不是空的,那么得到第一个元素的长度,如下所示:

 int len = array[0].length// the length of the second one

#3


0  

Here's a way to iterate over elements in a 2D array:

这是迭代2D数组中元素的方法:

for(double[] row : array)
{
  for(double element : row)
  {
     // Use element here.
  }
}

Its a row wise iteration. So if array is like:

它是一个行的迭代。所以如果数组是这样的:

double[][] array = {{1.2, 3.4}, {4.5, 5.6}};

Then element will have 1.2, 3.4, 4.5, 5.6 values in it at each iteration respectively.
Safe, fast, clean and concise.

然后,元素在每次迭代时将分别具有1.2,3.4,4.5,5.6的值。安全,快速,简洁。

#1


2  

Your inner for loop should check the length of the inner array

你的内部for循环应该检查内部数组的长度

for(int i=0; i < array.length; i++) {
        for(int j=0; j < array[i].length; j++) {
            //
        }
}

Or use foreach

或者使用foreach

for(double[] row : array) {
  for(double cell : row) {
     // 
  }
}

#2


0  

To get the size of the first dimension you don't need loop , just make this

要获得第一个维度的大小,您不需要循环,只需这样做

 int len = array.length/// the length of the first list

but if you want to get the size of the second dimension , and the array not empty so get the length of the first element , like this :

但是如果你想获得第二个维度的大小,并且数组不是空的,那么得到第一个元素的长度,如下所示:

 int len = array[0].length// the length of the second one

#3


0  

Here's a way to iterate over elements in a 2D array:

这是迭代2D数组中元素的方法:

for(double[] row : array)
{
  for(double element : row)
  {
     // Use element here.
  }
}

Its a row wise iteration. So if array is like:

它是一个行的迭代。所以如果数组是这样的:

double[][] array = {{1.2, 3.4}, {4.5, 5.6}};

Then element will have 1.2, 3.4, 4.5, 5.6 values in it at each iteration respectively.
Safe, fast, clean and concise.

然后,元素在每次迭代时将分别具有1.2,3.4,4.5,5.6的值。安全,快速,简洁。