请用java语言编写程序使结果打印出:“1 2 3 4 5 6 20 21 22 23 24 7 19 32 33 34 25 8 18 31 36 35 26 9 17 30 29 28 27 10 16 15 14 13 12 11
时间: 2024-01-04 20:04:34 浏览: 23
以下是使用Java编写的程序,以按照您所需的格式打印结果:
```java
public class NumberPattern {
public static void main(String[] args) {
int n = 6; // 设置数字的总行数
int[][] matrix = new int[n][n]; // 创建一个二维数组来存储数字
int num = 1;
int startRow = 0, endRow = n - 1, startCol = 0, endCol = n - 1;
while (num <= n * n) {
// 从左到右
for (int i = startCol; i <= endCol; i++) {
matrix[startRow][i] = num++;
}
startRow++;
// 从上到下
for (int i = startRow; i <= endRow; i++) {
matrix[i][endCol] = num++;
}
endCol--;
// 从右到左
for (int i = endCol; i >= startCol; i--) {
matrix[endRow][i] = num++;
}
endRow--;
// 从下到上
for (int i = endRow; i >= startRow; i--) {
matrix[i][startCol] = num++;
}
startCol++;
}
// 打印结果
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
运行该程序将打印出您所需的结果:
```
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
```
希望这能满足您的要求!