我想计算二维数组中行和列的长度。我知道如何执行行部分,但是我不知道如何找到此数组中列的长度。
public class array2D {
public static void main(String args[]) {
int maxNumberOfColumns = 8;
Integer[][] j = {
{2, 4, 8, 5, 1, 3, 7, 2},
{6, 7, 4, 8, 2},
{2, 3, 5, 9, 7, 1}};
for (int row = 0; row < j.length; row++) {
for (int col = 0; col < j[row].length; col++) {
System.out.print(j[row][col] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("------------");
System.out.println();
for (int row = 0; row < j.length; row++) {
System.out.println("row "+row+" has "+j[row].length+" elements");
}
System.out.println();
for (int col = 0; col < maxNumberOfColumns; col++) {
//code I don't know
}
}
}
最佳答案
您可以将最后一个 for 循环更改为下面的内容以打印每列的计数。我在这里使用内部循环来计算元素数量
for (int col = 0; col < maxNumberOfColumns; col++) {
int count = 0;
for (int i = 0; i < j.length; i++) {
if (j[i].length > col) {
count++;
}
}
System.out.println("Column " + (col + 1) + " has " + count + " elements");
}
另一种解决方案是使用
计算第一个循环中的最小列数minNumberOfColumns = length < minNumberOfColumns ? length : minNumberOfColumns;
然后将最后一个循环更改为
System.out.println("Column 1 to " + minNumberOfColumns + " has " + j.length + " elements");
for (int col = minNumberOfColumns; col < maxNumberOfColumns; col++) {
int count = 0;
for (int i = 0; i < j.length; i++) {
if (j[i].length > col) {
count++;
}
}
System.out.println("Column " + (col + 1) + " has " + count + " elements");
}
关于java - 如何计算不规则二维数组的列长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61422122/