我需要使用多维数组打印出以下数据:
5 4 3 2 1
10 9 8 7 6
15 14 13 12 11
20 19 18 17 16
25 24 23 22 21
我使用的编程语言是Java。这是我到目前为止所拥有的:
public class Problem3 {
public static void main(String[] args) {
int[][] prob3 = new int[5][5];
for(int row = 0; row < prob3.length; row++){
System.out.println();
for(int col = 0; col < prob3[row].length; col++){
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}
}
}
当我将其打印到屏幕上时,我得到:
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
我不知道如何操作这些数字,以便它们按照我想要的方式显示。我真的很想了解这是如何运作的。如果我这样做完全错误,请告诉我。感谢您提前提供的帮助。
最佳答案
如果你想向后迭代列,你必须将列循环的起始值设置为最后一个索引,检查它是否仍然大于或等于0,并在每次迭代时减少col
.
像这样:
int[][] prob3 = new int[5][5];
for (int row = 0; row < prob3.length; row++) {
System.out.println();
for (int col = prob3[row].length - 1; col >= 0; col--) {
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}
关于java - 在 Java 中组织 2D 整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748720/