import java.util.InputMismatchException;
import java.util.Scanner;
/**
* 回形数。
* 要求:输入一个数,输出对应的回形数组。
* 如:输入: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
*/
public class ClipNumber {
public static void main(String[] args) {
do {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a positive integer (enter 0 to exit):");
int n = scanner.nextInt();
if (n == 0) {
return;
}
int[][] array = new int[n][n];
int i = 0;
int j = 0;
int count = 1;
int direction = 1;
int minI = 0;
int minJ = 0;
int maxI = n - 1;
int maxJ = n - 1;
while (count <= n * n) {
switch (direction) {
case 1:
if (minJ <= j && j <= maxJ) {
array[minI][j++] = count++;
} else {
minI++;
i++;
direction = 2;
j--;
}
break;
case 2:
if (minI <= i && i <= maxI) {
array[i++][maxJ] = count++;
} else {
maxJ--;
j--;
direction = 3;
i--;
}
break;
case 3:
if (minJ <= j && j <= maxJ) {
array[maxI][j--] = count++;
} else {
maxI--;
i--;
direction = 4;
j++;
}
break;
case 4:
if (minI <= i && i <= maxI) {
array[i--][minJ] = count++;
} else {
minJ++;
j++;
direction = 1;
i++;
}
break;
default:
break;
}
}
int digits = String.valueOf(n * n).length();
for (int[] arrayI : array) {
for (int intJ : arrayI) {
System.out.printf("%1$-" + (digits + 1) + "s", intJ);
}
System.out.println();
}
} catch (InputMismatchException | NegativeArraySizeException e) {
System.out.println("The input is not a positive integer.");
}
} while (true);
}
}
Java 回形数
最新推荐文章于 2023-10-23 22:02:38 发布