我用它来反转一个int数组
int[] a = new int[10];
System.out.print("a[i]: ");
for (int i = 0 ; i < 10 ; i++) {
a[i] = i + 1;
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("a[i] reverse: ");
for (int i = 0 ; i < a.length/2 ; i++) {
int temp = a[i];
a[i] = a[a.length-i-1];
a[a.length-i-1] = temp;
System.out.print(a[i]+" ");
结果是这样的:
a[i]: 1 2 3 4 5 6 7 8 9 10
a[i] reverse: 10 9 8 7 6
代码有什么问题?为什么反向版本中的一半数组消失了? 谢谢
答案 0 :(得分:2)
完成反转后,打印数组a
,如下所示:
//reverse it
System.out.print("a[i] reverse: ");
for (int i = 0; i < a.length / 2; i++) {
int temp = a[i];
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
//now print it
System.out.println(Arrays.toString(a));
其中
输出:
a[i]: 1 2 3 4 5 6 7 8 9 10
a[i] reverse: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
答案 1 :(得分:0)
for(int i = 0; i < a.length / 2 ; i ++)是错误的。循环状态计数是数组大小的一半。这样就可以打印数组的一半。你必须写
为(int i = 0; i
答案 2 :(得分:0)
您也可以通过替换代码来实现
for (int i = 0 ; i < a.length/2 ; i++) {
int temp = a[i];
a[i] = a[a.length-i-1];
a[a.length-i-1] = temp;
System.out.print(a[i]+" ");
with ..
System.out.println(a.length);
for(int i=a.length;i>0;i--){
System.out.print(a[i-1]+" ");
}