Java数组反转程序未输出预期结果,报ArrayIndexOutOfBoundsException
问题分析与修复
错误原因
- 数组索引越界:Java数组索引从0开始,长度为n的数组最大有效索引是
n-1。你的反转循环中使用arr[n - i],当i=0时,索引为n,超出了数组的有效范围,直接触发ArrayIndexOutOfBoundsException。 - 逆序逻辑错误:即使忽略越界问题,原循环的索引计算也无法得到正确的逆序。比如n=5时,i从0到4,
n-i依次是5、4、3、2、1,对应数组元素是越界值、arr[4]、arr[3]、arr[2]、arr[1],完全不是预期的逆序结果。
修复方案
方案一:调整索引计算
将反转循环中的索引改为n - 1 - i,确保每次取的都是有效索引,且从数组末尾向前遍历:
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(); } // 修复后的反转输出逻辑 for(int i = 0; i < n; i++) { System.out.print(arr[n - 1 - i] + " "); } sc.close(); // 关闭Scanner资源 } }
方案二:从数组末尾直接遍历
更直观的方式是让循环变量从数组最后一个索引开始,递减到0:
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(); } // 从末尾遍历输出 for(int i = n - 1; i >= 0; i--) { System.out.print(arr[i] + " "); } sc.close(); } }
验证效果
输入1 2 3 4 5时,两种方案都会输出5 4 3 2 1,且不会抛出异常。
内容的提问来源于stack exchange,提问作者SANKAR S
相关产品推荐
相关产品推荐

