我需要编写一个程序,在用户输入行和列时输出以下内容。以下示例适用于 4x4 矩阵:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
还是个初学者,发现那些数组真的很难。
它适用于下面的代码,但我不确定是否允许像这样填充 - 先列再行。
我无法找到一种方法来处理:
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
我使用的代码:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
array[i][j]=counter;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
最佳答案
您要在此处使用的技巧是使用函数来计算给定单元格的值。该功能相对简单......对于每一行,值增加行数。例如,有 4 行,所以每行的值增加 4..... 1, 5, 9, 13, ....
因此,您的代码可以简化为:
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print((r + 1 + (c * rows)) + " ");
}
System.out.println();
}
不需要任何阵列或临时存储等。
重申一下,每个单元格的值是行(从索引 1 开始,而不是 0)加上基于列号(从 0 开始)的“偏移量”。
你可以看到它在这里运行:http://ideone.com/RqPgbN
关于java - 方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298484/