好的,所以我有我的代码,一切都很好,但我没看到为什么我的输出给了我one
而不是public class ICE17 {
static //Examine the following program:
class ArrayProblems {
public static void main(String[] args) {
int[] val = { 0, 1, 2, 3 };
int sum = 0; //write code here
for (int i = 0; i < val.length; i++) {
sum += val[i];
}
System.out.println("Sum of all numbers = " + sum);
reverse();
}
public static void reverse() {
int[] val = { 0, 1, 2, 3 };
//int temp=0;
System.out.println("Original Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);
// write code here to reverse the order of the numbers in the array
for (int i = 0; i < val.length / 2; i++) {
int temp = val[i];
val[i] = val[val.length - 1 - i];
val[val.length - 1 - i] = temp;
System.out.println("Reversed Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);
}
}
}
}
。最后一个是正确的,但逆转的第一个输出有点混淆。
p:commandButton
答案 0 :(得分:2)
检查你的花括号!
for (int i = 0; i < val.length / 2; i++) {
int temp = val[i];
val[i] = val[val.length - 1 - i];
val[val.length - 1 - i] = temp;
System.out.println("Reversed Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);
}
正如您所看到的,每次for循环运行时,您都会打印出反向数组。
在第一个循环中没有完成反转,所以它打印出来有点搞笑。
答案 1 :(得分:2)
Erick已经回答了解决打印问题的权利。您正在for循环中打印数组,因此它将打印长度/ 2次。
你的反向方法正在创建一个本地数组并将其反转的其他事情。如果你真的想要反转在main方法中创建的数组,那么编写一个将数组作为输入的函数,如下所示:
public class ICE17 {
public static void reverseArray(int[] val) {
for (int i = 0; i < val.length / 2; i++) {
int temp = val[i];
val[i] = val[val.length - 1 - i];
val[val.length - 1 - i] = temp;
}
}
public static void printArray(int[] val) {
for(int i: val) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int arr[] = { 0, 1, 2, 3 };
System.out.println("Array before reverse");
printArray(arr);
reverseArray(arr);
System.out.println("Array after reverse");
printArray(arr);
}
}