Java程序在数组翻转时没有输出预期结果
我在尝试用Java编写一个用于反转数组的程序。我的目标是输入一个数组并以相反的顺序打印出来。
如果输入是:
1 2 3 4 5
期望的输出:
5 4 3 2 1
实际输出
程序输出了错误的数值,或者有时会重复元素。
我尝试过的办法
我使用一个循环从数组末尾遍历,但我觉得我的逻辑是错的。
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter elements:");
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Reversing array
for(int i = 0; i < n; i++) {
System.out.print(arr[n - i] + " ");
}
}
}
问题
我得到一个 ArrayIndexOutOfBoundsException。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at ReverseArray.main(ReverseArray.java:17)
提问
我的数组反转逻辑哪里出错?我该如何修正这个错误?
解决方案
在Java中,数组下标从0 开始,因此最后一个有效下标是 n - 1,而不是 n。在你的循环中,这一行:
arr[n - i]
会造成问题,因为当 i = 0 时,它会访问 arr[n],这越界并会抛出一个 ArrayIndexOutOfBoundsException。
要修复这个问题,你只需要减去1:
for (int i = 0; i < n; i++) {
System.out.print(arr[n - 1 - i] + " ");
}
或者你也可以向后遍历:
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。