在Java中计算二维数组中的个数:获取外层数组的行数。对于每一行,获取内层数组的列数。将所有内层数组的长度相加,得到元素总数。
Java中计算二维数组中的个数
在Java中,计算二维数组中的元素个数非常简单:
方法
length属性获取外层数组的长度(行数)。length属性获取内层数组的长度(列数)。示例代码
int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// 计算外层数组的行数
int numRows = myArray.length;
// 变量用于存储元素总数
int totalElements = 0;
// 遍历每一行
for (int i = 0; i < numRows; i++) {
// 计算内层数组的列数
int numCols = myArray[i].length;
// 将列数添加到元素总数中
totalElements += numCols;
}
// 输
出元素总数
System.out.println("元素总数:" + totalElements);输出
元素总数:9