第八章第二十二题(偶数个1)(Even 1)
-
*8.22(偶数个1)编写一个程序,产生一个6x6的填满0和1的二维矩阵,显示该矩阵,检测是否每行以及每列中有偶数个1.
*8.22(Even 1)Write a program to generate a 6x6 two-dimensional matrix filled with 0 and 1, display the matrix, detect whether there are even 1 in each row and column -
参考代码:
package chapter08; public class Code_22 { public static void main(String[] args) { int[][] matrix = new int[6][6]; for (int i = 0;i < 6;i++) for (int j = 0;j < 6;j++) matrix[i][j] = (int)(Math.random() * 2); for (int i = 0;i < 6;i++) { for (int j = 0; j < 6; j++) System.out.print(matrix[i][j] + " "); System.out.println(); } int countRow; int countColumn = 0; for (int i = 0;i < 6;i++) { countRow = 0; for (int j = 0; j < 6; j++){ if (matrix[i][j] == 1) countRow++; } if (countRow % 2 == 0) System.out.println("The " + (i + 1) + " row has even 1"); } for (int i = 0;i < 6;i++) { countColumn = 0; for (int j = 0; j < 6; j++){ if (matrix[j][i] == 1) countColumn++; } if (countColumn % 2 == 0) System.out.println("The " + (i + 1) + " column has even 1"); } } }
-
结果显示:
1 1 0 0 1 0 1 0 0 1 1 1 0 1 0 0 1 0 0 1 0 0 1 1 0 1 0 0 0 1 0 0 1 1 1 0 The 2 row has even 1 The 3 row has even 1 The 5 row has even 1 The 1 column has even 1 The 2 column has even 1 The 4 column has even 1 Process finished with exit code 0