Java数组反转时出现ArrayIndexOutOfBoundsException,求错误定位与修正
数组反转时ArrayIndexOutOfBoundsException的问题分析与修复
错误点分析
- 循环变量类型误用:数组索引是整数类型,没必要用
double作为循环变量,强制转换还会引入额外风险。 - 反转索引计算错误:
reversedTArray[1-(int)i]当i≥2时会生成负数索引,直接触发数组越界;testArray[10-(int)i]的写法会遗漏原数组第一个元素(索引0的3.5),因为循环i从1到9,10-i最小为1,取不到testArray[0]。 - 增强for循环使用错误:增强for循环里的
i是数组元素值,不是索引。你把元素值转成int当索引用(比如99.7转成99),远超出数组索引范围(0-9),必然越界。
修正后的代码
public class Main { public static void main(String[] args) { double[] testArray = new double[]{3.5, 7.9, 0.0, -7.9, 10.99, 78.9, 66.8, 19.01, 18.9, 99.7}; double[] reversedTArray = new double[testArray.length]; // 用原数组长度,避免硬编码数值 // 正确的反转逻辑:原数组末尾元素对应新数组开头 for (int i = 0; i < testArray.length; i++) { reversedTArray[i] = testArray[testArray.length - 1 - i]; } // 直接遍历输出反转后的数组元素 for (double num : reversedTArray) { System.out.println(num); } } }
修正后输出
99.7 18.9 19.01 66.8 78.9 10.99 -7.9 0.0 7.9 3.5
注:你期望输出里的1.0应为笔误,原数组对应位置是0.0,修正后的代码会输出正确的反转结果。
内容的提问来源于stack exchange,提问作者Turbo
相关产品推荐
相关产品推荐

