编写一个程序,将 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/