用数组和字符串,利用随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组,用java实现
时间: 2023-05-31 21:07:01 浏览: 94
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];
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
shuffle(nums);
int index = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
magicSquare[i][j] = nums[index];
index++;
}
}
print(magicSquare);
}
public static void shuffle(int[] nums) {
Random random = new Random();
for (int i = nums.length - 1; i >= 0; i--) {
int j = random.nextInt(i + 1);
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
public static void print(int[][] magicSquare) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
}
}
```
输出:
```
9 3 2
7 5 6
1 4 8
```
阅读全文