Java 输出方阵 - 代码示例及运行结果
以下是一个用Java编写的方阵输出程序:
import java.util.Scanner;
public class MatrixOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
int[][] matrix = new int[n][n];
int num = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = num;
num++;
}
}
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×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×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/fGcp 著作权归作者所有。请勿转载和采集!