用数组和字符串,不使用指针,利用随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组,用java实现
时间: 2023-05-31 19:07:02 浏览: 92
JAVA中的二维数组
5星 · 资源好评率100%
```
public class MagicSquare {
public static void main(String[] args) {
int[][] magicSquare = new int[3][3];
// 随机生成1~9的数字填充二维数组
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare[i].length; j++) {
magicSquare[i][j] = (int) (Math.random() * 9 + 1);
}
}
// 输出原始的二维数组
System.out.println("原始的二维数组:");
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare[i].length; j++) {
System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
// 计算每行、每列、每个对角线的和
int[] rowSum = new int[3];
int[] colSum = new int[3];
int diagonalSum1 = 0;
int diagonalSum2 = 0;
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare[i].length; j++) {
rowSum[i] += magicSquare[i][j];
colSum[j] += magicSquare[i][j];
if (i == j) {
diagonalSum1 += magicSquare[i][j];
}
if (i + j == 2) {
diagonalSum2 += magicSquare[i][j];
}
}
}
// 判断是否满足条件
boolean isMagic = true;
for (int i = 0; i < rowSum.length; i++) {
if (rowSum[i] != 15 || colSum[i] != 15) {
isMagic = false;
break;
}
}
if (diagonalSum1 != 15 || diagonalSum2 != 15) {
isMagic = false;
}
// 输出结果
if (isMagic) {
System.out.println("满足条件的二维数组:");
for (int i = 0; i < magicSquare.length; i++) {
for (int j = 0; j < magicSquare[i].length; j++) {
System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
} else {
System.out.println("没有满足条件的二维数组。");
}
}
}
```
阅读全文