2016-12-04 64 views
-7

我有一个2维数组,所以数组的数组。数组DONT的数组长度相同。 这里的一个例子:如何遍历锯齿阵列中的每个元素?

double[][] multi = new double[][] { 
    { 10, 20, 30, 40, 50 }, 
    { 1.1, 2.2, 3.3, 4.4 }, 
    { 1.2, 3.2 }, 
    { 1, 2, 3, 4, 5, 6, 7, 8, 9 } 
}; 

我该如何循环通过列? (我爱:10 1.1 1.2 1

+3

欢迎堆栈溢出!看起来你正在寻求作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 –

+1

每一行都是一个数组。一个数组有一个'length'属性。 –

+2

你的问题*不清楚*。例如,它会在列3上表现如何(假设您要打印列)?它应该打印'30,3.3,null,3'吗? – Gendarme

回答

1

你能做到像这样的迭代整个阵列逐列

// Get the maximum number of columns among all rows. 
int maximumColumns = 0; 
for (double[] row : multi) { 
    if (row.length > maximumColumns) { 
     maximumColumns = row.length; 
    } 
} 

for (int column = 0; column < maximumColumns ; column++) { 
    for (int row = 0; row < multi.length; row++) { 
     if (column >= multi[row].length) { 
      // There is no value for this column. 
     } else { 
      // Do stuff here with multi[row][column]. 
     } 
    } 
} 

对于特异性存在于所有的行IC柱做到这一点:

int columnToIterate = // Your column. 
for (int row = 0; row < multi.length; row++) { 
    if (columnToIterate < multi[row].length) { 
     // Do stuff here with multi[row][columnToIterate]. 
    } 
} 
+0

第一个例子是你想要的。注意,如果你想忽略不存在的值,你可以使用if(column thatguy

+0

请注意,如果'multi [row]'为null(并且由于数组可以为null,这是一种可能性),'multi [row] .length'将会引发异常。 – NightOwl888

3

二维数组是数组的数组。所以可以作为迭代:

for (double[] row: multi) { 
     for(double value: row) { 
     } 
    } 
2

这样做:

for(int i=0; i<multi.length; i++) { 
      for(int j=0; j<multi[i].length; j++) { 
       System.out.println("Values at multi["+i+"]["+j+"] is "+multi[i][j]); 
      } 
     }