Java 生成方阵:代码示例及运行结果
下面是一个使用 Java 编写的程序,可以根据输入的数字生成对应大小的方阵并输出。
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
int count = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = count;
count++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
运行结果截图:
输入 5:
5
输出:
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
输入 7:
7
输出:
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 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49
原文地址: https://www.cveoy.top/t/topic/fGcx 著作权归作者所有。请勿转载和采集!