java - 查找二维数组中 1 最多的索引和列

标签 java arrays multidimensional-array

编写一个程序,将 0 和 1 随机插入到 4 x 4 数组矩阵中,然后需要返回 1 出现最多的列和行索引。我的第一个检查行的方法工作正常,但我在第二个检查列的方法中遇到了问题。

错误表示找不到变量“col”的符号。

public class AssignmentEight_MultiArray {
 public static void main(String[] args) {

 System.out.println("Beginning to insert random integers into array..");

 // Declare array matrix
 int[][] matrix = new int[4][4];

 // For loop to insert integers into the array 
 for (int row = 0; row < matrix.length; row++) {
  for (int col = 0; col < matrix[row].length; col++) { 
  int ranNum = (Math.random() < 0.5) ? 0:1;
  matrix[row][col] = ranNum;
  }
 }

// Display contents of the array
System.out.println("The values of the array are printed below");

showArray(matrix);

System.out.println();

System.out.print("The largest row index: " + scanRow(matrix) + "\n");
System.out.print("The largst column index: " + scanColumn(matrix) + "\n");


} // end main

// method to show array contents 
private static void showArray(int[][] array) {
 for (int row = 0; row < array.length; row++) {
   for (int col = 0; col < array[row].length; col++)
     System.out.print(array[row][col] + "\t");
   System.out.println();
 }
}

// row index method 
private static int scanRow(int[][] array) {
 int result = -1;
 int highest = -1;

for (int row = 0; row < array.length; row++) {
 int temp = 0;
 for (int col = 0; col < array[row].length; col++) {
 // assign current location to temp variable
 temp = temp + array[row][col];
 }

if (temp > highest) {
  highest = temp;
  result = row;
}

}
return result;
} // end of row method

// column index method
private static int scanColumn(int[][] array) {
 int result = -1;
 int highest = -1;

for (int row = 0; row < array.length; row++) {
int temp = 0;  
for (int col = 0; col < array[row].length; col++) {
// assing current location to temp variable
temp = temp + array[row][col];
}

if (temp > highest) {
 highest = temp;
 result = col;
}

}
 return result;
} // end column method  


} // end class 

最佳答案

我认为你正在谈论由这段代码引起的错误:

            for (int col = 0; col < array[row].length; col++) {
// assing current location to temp variable
                temp = temp + array[row][col];
            }

            if (temp > highest) {
                highest = temp;
                result = col;
            }

如果您发现大括号在 result = col;
之前关闭 col 不存在于 for 循环之外。

关于java - 查找二维数组中 1 最多的索引和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847351/

相关文章:

java - 如何在 Android 中显示两列 ListView?

java - XML Schematron 中的换行符和空格

Java:预览 HttpPost 请求

php - 你如何在 wordpress 中使用 wp_Query 输出 JSON?

c - 随机排列数组(段错误)

c - 如何将二维数组的高度和宽度作为参数传递给方法?

javascript - 嵌套数组到字符串javascript

javascript - 如何截取整个网页的屏幕截图?

php - 标准类对象到数组

php - 使用另一个数组更新现有键的多维数组 PHP