案例一:创建一个长度为6的int型数组,要求取值为1-30,同时元素值各不相同
方式一实现:
1 public static void main(String[] args) {
2 int[] arr = new int[6];
3
4 for (int i = 0; i < arr.length; i++) {
5 arr[i] = (int)(Math.random()*30 + 1);
6
7 boolean flag = false;
8 while(true) {
9
10 for (int j = 0; j < i; j++) {
11 if (arr[j] == arr[i]) {
12 flag = true;
13 break;
14 }
15 }
16
17 if (flag) {
18 arr[i] = (int)(Math.random()*30 + 1);
19 flag = false;
20 continue;
21 }
22 break;
23 }
24 }
25
26 System.out.println(Arrays.toString(arr));
27 }
方式二实现:
1 public static void main(String[] args) {
2 int[] arr = new int[6];
3
4 for (int i = 0; i < arr.length; i++) {
5 arr[i] = (int)(Math.random()*30 + 1);
6
7 for (int j = 0; j < i; j++) {
8 if (arr[i] == arr[j]) {
9 i--;
10 break;
11 }
12 }
13 }
14
15 System.out.println(Arrays.toString(arr));
16 }
案例二:回形数格式方阵的实现
从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如: 输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
方式一:
1 private static void method1() {
2 Scanner sc = new Scanner(System.in);
3
4 System.out.println("请输入一个数字:");
5 int len = sc.nextInt();
6 int[][] arr = new int[len][len];
7
8 int s = len * len;
9
10 /*
11 * k = 1:向右 k = 2:向下 k = 3:向左 k = 4:向上
12 */
13 int k = 1;
14 int i = 0, j = 0;
15
16 for (int m = 1; m <= s; m++) {
17 if (k == 1) {
18 if (j < len && arr[i][j] == 0) {
19 arr[i][j++] = m;
20 } else {
21 k = 2;
22 i++;
23 j--;
24 m--;
25 }
26 } else if (k == 2) {
27 if (i < len && arr[i][j] == 0) {
28 arr[i++][j] = m;
29 } else {
30 k = 3;
31 i--;
32 j--;
33 m--;
34 }
35 } else if (k == 3) {
36 if (j >= 0 && arr[i][j] == 0) {
37 arr[i][j--] = m;
38 } else {
39 k = 4;
40 i--;
41 j++;
42 m--;
43 }
44 } else if (k == 4) {
45 if (i >= 0 && arr[i][j] == 0) {
46 arr[i--][j] = m;
47 } else {
48 k = 1;
49 i++;
50 j++;
51 m--;
52 }
53 }
54 }
55
56
57 // 遍历
58 for (int m = 0; m < arr.length; m++) {
59 for (int n = 0; n < arr[m].length; n++) {
60 System.out.print(arr[m][n] + " ");
61 }
62 System.out.println();
63 }
64
65 }
方式二:
1 private static void fn2() {
2 Scanner sc = new Scanner(System.in);
3
4 System.out.println("请输入一个数字:");
5 int n = sc.nextInt();
6 //int n = 7;
7 int[][] arr = new int[n][n];
8
9 int count = 0; // 要显示的数据
10 int maxX = n - 1; // x轴的最大下标
11 int maxY = n - 1; // Y轴的最大下标
12 int minX = 0; // x轴的最小下标
13 int minY = 0; // Y轴的最小下标
14 while (minX <= maxX) {
15 for (int x = minX; x <= maxX; x++) {
16 arr[minY][x] = ++count;
17 }
18 minY++;
19 for (int y = minY; y <= maxY; y++) {
20 arr[y][maxX] = ++count;
21 }
22 maxX--;
23 for (int x = maxX; x >= minX; x--) {
24 arr[maxY][x] = ++count;
25 }
26 maxY--;
27 for (int y = maxY; y >= minY; y--) {
28 arr[y][minX] = ++count;
29 }
30 minX++;
31 }
32
33 for (int i = 0; i < arr.length; i++) {
34 for (int j = 0; j < arr.length; j++) {
35 String space = (arr[i][j] + "").length() == 1 ? "0" : "";
36 System.out.print(space + arr[i][j] + " ");
37 }
38 System.out.println();
39 }
40
41 }