用java利用随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组
时间: 2024-05-06 14:19:43 浏览: 65
JAVA基础随机整数的生成
5星 · 资源好评率100%
```java
import java.util.Arrays;
import java.util.Random;
public class MagicSquare {
public static void main(String[] args) {
int[][] magicSquare = new int[3][3];
Random random = new Random();
// 随机生成1~9的数字
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// 打乱数字顺序
for (int i = 0; i < 9; i++) {
int j = random.nextInt(9);
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
// 填充二维数组
int index = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
magicSquare[i][j] = numbers[index++];
}
}
// 计算每行、每列、每个斜线的和
int[] rowSum = new int[3];
int[] colSum = new int[3];
int[] diagonalSum = new int[2];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rowSum[i] += magicSquare[i][j];
colSum[j] += magicSquare[i][j];
if (i == j) {
diagonalSum[0] += magicSquare[i][j];
}
if (i + j == 2) {
diagonalSum[1] += magicSquare[i][j];
}
}
}
// 判断是否符合要求
boolean isMagicSquare = true;
for (int i = 0; i < 3; i++) {
if (rowSum[i] != 15 || colSum[i] != 15) {
isMagicSquare = false;
break;
}
}
if (diagonalSum[0] != 15 || diagonalSum[1] != 15) {
isMagicSquare = false;
}
// 输出结果
if (isMagicSquare) {
for (int[] row : magicSquare) {
System.out.println(Arrays.toString(row));
}
} else {
System.out.println("无法生成符合要求的3*3幻方。");
}
}
}
```
阅读全文