java第五章5.39
时间: 2023-11-13 16:55:52 浏览: 103
好的,你的问题是关于Java第五章的5.39题。这道题目要求你编写一个程序,输入一个整数n,然后输出一个n行n列的矩阵,矩阵中的元素按照从外向内递增的顺序依次填充。
下面是Java代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
int num = 1;
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
for (int i = top + 1; i <= bottom; i++) {
matrix[i][right] = num++;
}
if (left < right && top < bottom) {
for (int i = right - 1; i >= left; i--) {
matrix[bottom][i] = num++;
}
for (int i = bottom - 1; i > top; i--) {
matrix[i][left] = num++;
}
}
left++;
right--;
top++;
bottom--;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
阅读全文