我目前只能执行一项任务,在该任务中,我必须反转数组中元素的顺序。 但是问题是我只能得到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]);
}
}
}
答案 0 :(得分:1)
您没有撤销订单,只是尝试从头开始阅读。
要取消顺序
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++;
}
}
答案 1 :(得分:0)
public class ReverseArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
应该可以解决问题。