用java1. 利用随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组
时间: 2024-05-08 20:16:05 浏览: 64
```
public class Main {
public static void main(String[] args) {
int[][] arr = new int[3][3];
int[] sumRow = new int[3];
int[] sumCol = new int[3];
int sumDiagonal = 0;
int sumAntiDiagonal = 0;
// 生成随机数组并计算行、列、对角线上的和
while (true) {
arr = generateRandomArray();
for (int i = 0; i < 3; i++) {
sumRow[i] = 0;
sumCol[i] = 0;
sumDiagonal += arr[i][i];
sumAntiDiagonal += arr[i][2-i];
for (int j = 0; j < 3; j++) {
sumRow[i] += arr[i][j];
sumCol[i] += arr[j][i];
}
}
if (sumRow[0] == 15 && sumRow[1] == 15 && sumRow[2] == 15
&& sumCol[0] == 15 && sumCol[1] == 15 && sumCol[2] == 15
&& sumDiagonal == 15 && sumAntiDiagonal == 15) {
break;
}
}
// 输出结果
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
// 生成随机数组
public static int[][] generateRandomArray() {
int[][] arr = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = (int)(Math.random() * 9) + 1;
}
}
return arr;
}
}
```
阅读全文