题目
题目描述与运行示例
8.10(最大的行和列)编写一个程序,在一个44的矩阵中随机填入0和1,打印该矩阵,分别找到第一个具有最多1的行和列。下面是一个运行示例:
1111
0101
1101
1001
The largest row index: 0
The largest column index: 3
破题
- 声明一个4*4矩阵
- 使用双层循环给矩阵赋随机值0和1((int)(Math.random()*2))并打印(如遇到列结束则换行)
- 初始化两个int型对象,分别保存1最多的行下标和1的个数;再初始化1个int型对象,用于临时保存1的个数
- 使用循环找1最多的行(双层循环)
- 找1最多的列与3~4步相似,只需要修改循环即可
- 输出最多1的行、列
代码
public class Test8_10 {
public static void main(String[] args) {
//1. 声明一个4*4矩阵
int[][] array = new int[4][4];
//2. 使用双层循环给矩阵赋随机值0和1((int)(Math.random()*2))并打印(如遇到列结束则换行,最后一行不换)
for (int i = 0 ; i < 4 ; i++){
for (int j = 0 ; j < 4; j++){
array[i][j] = (int)(Math.random()*2);
System.out.print(array[i][j]);
}
System.out.println();
}
//3. 初始化两个int型对象,分别保存1最多的行下标和1的个数;再初始化1个int型对象,用于临时保存1的个数
int largest_row = 0;
int count_row = 0;
int temp_row = 0;
//4. 使用循环找1最多的行(双层循环)
for (int i = 0 ; i < 4 ; i++){
temp_row = 0;
for (int j = 0 ; j < 4; j++){
if (array[i][j] == 1){
++temp_row;
}
}
if (count_row < temp_row){
count_row = temp_row;
largest_row = i;
}
}
//5. 找1最多的列与3~4步相似,只需要修改循环即可
int largest_col = 0;
int count_col = 0;
int temp_col = 0;
for (int j = 0 ; j < 4 ; j++){
temp_col = 0;
for (int i = 0 ; i < 4; i++){
if (array[i][j] == 1){
++temp_col;
}
}
if (count_col < temp_col){
count_col = temp_col;
largest_col = j;
}
}
//6. 输出最多1的行、列
System.out.println("The largest row index: " + largest_row);
System.out.println("The largest column index: " + largest_col);
}
}