-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomArray.java
More file actions
32 lines (30 loc) · 1.01 KB
/
RandomArray.java
File metadata and controls
32 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[][] matrix = new int[3][3];
boolean[] used = new boolean[10];
// 标记1-9是否已使用
Random random = new Random();
int num;
// 填充3x3数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
do {
// 随机生成数字
num = random.nextInt(9) + 1;
} while (used[num]); // 数字已使用,重新生成
// 标记为已使用,并填入数组
used[num] = true;
matrix[i][j] = num;
}
}
// 输出数组
System.out.println("3x3随机数组(标记数组方法):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}