gpt4 book ai didi

java - 反转数组中元素的顺序

转载 作者:行者123 更新时间:2023-12-02 01:04:18 25 4
gpt4 key购买 nike

我目前陷入了一项任务,必须颠倒数组中元素的顺序。但问题是我只得到了 10 10 次而不是 10 9 8...

package JavaSection4;

public class Assignment4Nr2 {

public static void main(String[] args) {

int[] ranNum = new int[10];

ranNum[0] = 1;
ranNum[1] = 2;
ranNum[2] = 3;
ranNum[3] = 4;
ranNum[4] = 5;
ranNum[5] = 6;
ranNum[6] = 7;
ranNum[7] = 8;
ranNum[8] = 9;
ranNum[9] = 10;

for(int i = 0; i < ranNum.length; i++) {

int l = 0;

l = ranNum.length - 1;

System.out.println(ranNum[l]);
}
}
}

最佳答案

你并不是颠倒顺序,你只是想从最后开始阅读。

颠倒顺序将是

Integer[] integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ArrayUtils.reverse(integers);

通过使用适当的工具(在本例中为 apache-commons)。通过检查工具源代码可以很容易地了解它是如何完成的:

public static void reverse(Object[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
Object tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}

关于java - 反转数组中元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com