我正在尝试排列和打印一个从 500 开始到 1 停止的数组, 我已经用下面的代码试过了,但是这将从 1 开始打印输出到 500:
int [] aftel = new int [501];
for (int teller3 = 500; teller3 > 0; teller3--){
aftel[teller3] = teller3;
}
System.out.println(Arrays.toString(aftel));
但是使用下面的代码,数组将以正确的方式打印输出,但我试图在打印出值之前完全排列数组:
int [] aftel = new int [501];
for (int teller2 = 1; teller2 <= 500; teller2++){
optel500[teller2] = teller2;
System.out.print(optel500[teller2]+" ");
}
最佳答案
在您的第一个循环中,您使用teller3
作为索引和 值。这意味着索引 500 的值为 500,这与您想要的相反。
您还混淆了数组大小。
执行此操作的正确方法是直接执行循环并从 500 中减去该值
int [] aftel = new int [500];
for (int teller3 = 0; teller3 < 500; teller3++){
aftel500[teller3] = (500 - teller3) + 1;
}
或者对数组索引做同样的事情
int [] aftel = new int [500];
for (int teller3 = 500; teller3 > 0; teller3--){
aftel[500 - teller3] = teller3;
}
关于java - 如何在数组中排列从 500 到 1 的数组? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52626749/