作为Java的初学者,我在反转数组时遇到问题。
这是代码
public class Test {
public static void main(String[] args) {
int[] array = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
int x = array.length;
int[] y = new int[x];
for (int i = 0; i < x / 2; i++) {
int temp1 = array[i];
y[i] = array[x - i - 1];
array[i] = temp1;
System.out.println(y[i]);
}
}
}
结果必须为:
90、80、70、60、50、40、30、20、10
但我只能得到:
90、80、70、60
我该如何解决这个问题?
有什么好的资源可以教Java吗?
答案 0 :(得分:1)
在您的代码中,您仅遍历原始数组的一半,
public class Test {
public static void main(String[] args) {
int[] array = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
int x = array.length;
int[] y = new int[x];
for (int i = 0; i < x / 2; i++) { // traversing only half
int temp1 = array[i]; // statement 1
y[i] = array[x - i - 1]; // you just need this statement
array[i] = temp1; //statement 2
//Notice that statement 1 and 2 do nothing as a whole
System.out.println(y[i]);
}
}
}
如果您这样调整代码,
import java.util.*;
public class MyClass {
public static void main(String args[]) {
int[] array = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
int x = array.length;
int[] y = new int[x];
for (int i = 0; i < x; i++) {
//int temp1 = array[i];
y[i] = array[x - i - 1];
//array[i] = temp1;
}
System.out.println(Arrays.toString(y));
}
}
然后它将正常工作
答案 1 :(得分:-1)
for循环仅从i = 0迭代到i = array.Length / 2,并且由于其主体内只有一个print语句,因此仅打印数组前半部分的元素。
答案 2 :(得分:-1)
public class Test {
public static void main(String [] args){
int[] array = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
int x = array.length;
int[] y = new int[x];
for (int i = 0; i < x; i++) {
y[i] = array[x - i - 1];
System.out.println(y[i]);
}
}
}
由于需要反转整个数组,因此不需要迭代最多x / 2,而迭代到x(即数组的实际长度)将为您提供所需的结果。
对于Java教程,您可以here学习它