Java数组越界问题求助:自定义数组操作方法持续报错
数组越界错误的修复方案
你的代码触发数组越界异常的核心原因是循环条件写错了:
Java数组的索引从0开始,长度为n的数组,有效索引范围是0到n-1。你写的两个for循环都用了<= num.length的条件,当循环变量等于num.length时,访问num[num.length]就超出了数组的有效边界,直接触发ArrayIndexOutOfBoundsException。
修正后的代码
static void arrrays() { Scanner sn = new Scanner(System.in); /* arrays = stores multiples values of similar variables WAYS TO DECLEAR A ARRAY 1.String[] cars = new String[3]; 2.String[] cars={"Camaro","Corvette","Tesla"}; */ int size; System.out.println("Enter the size of the array ="); size=sn.nextInt(); int[] num= new int[size]; System.out.println("Created a Numerical Array"); // 修改循环条件为 x < num.length for (int x=0; x < num.length; x++) { System.out.println("Enter data into the " + x + " index = " ); num[x]=sn.nextInt(); } // 修改循环条件为 j < num.length for(int j=0; j < num.length; j++) { int temp2=j+1; System.out.println(temp2 +" index contains= "+num[j]); } /*//Printing arrays String[] cars={"Camaro","Corvette","Tesla"}; for(int i=0;i< cars.length;i++) { System.out.println(cars[i]); }*/ }
关键修改点
- 第一个循环:把
x<=num.length改为x < num.length,确保只访问0到num.length-1的有效索引 - 第二个循环:把
j<=num.length改为j < num.length,避免访问超出边界的数组元素
这样修改后,代码就能正常接收输入并打印数组内容,不会再触发越界错误。
内容的提问来源于stack exchange,提问作者Ashitosh bendre
相关产品推荐
相关产品推荐

