ArrayIndexOutOfBoundsException 是什么意思,我该如何摆脱它?这是触发异常的代码示例:
What does ArrayIndexOutOfBoundsException mean and how do I get rid of it? Here is a code sample that triggers the exception:
我一直在编写 java 中的一些代码,但我只是 运行 出错了,我不确定为什么,因为我只是 运行 一些代码就像这个,它工作得很好。
String [] month = {"Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
double [] temperature ={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double [] precipitation ={3.5, 3.4, 4.3, 2.9, 3.2, 6.8, 6.1, 6.6, 4.4, 2.5, 2.2, 2.6};
for( int index = 0; index < temperature.length; index++)
{
System.out.print(""+month [index] +". "+temperature [index]+" "+precipitation [index]);
System.out.println();
}
通过检查,我发现您的 month
数组缺少 May
月份,因此其中只有 11 个元素。结果,当你遍历temperature
数组中的12个元素时,你会在最终温度期间得到一个数组越界异常,因为在month
中那个位置没有对应的enter。
要解决此问题,只需确保 month
和 temperature
大小相同:
String [] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec" };
我一直在编写 java 中的一些代码,但我只是 运行 出错了,我不确定为什么,因为我只是 运行 一些代码就像这个,它工作得很好。
String [] month = {"Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
double [] temperature ={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double [] precipitation ={3.5, 3.4, 4.3, 2.9, 3.2, 6.8, 6.1, 6.6, 4.4, 2.5, 2.2, 2.6};
for( int index = 0; index < temperature.length; index++)
{
System.out.print(""+month [index] +". "+temperature [index]+" "+precipitation [index]);
System.out.println();
}
通过检查,我发现您的 month
数组缺少 May
月份,因此其中只有 11 个元素。结果,当你遍历temperature
数组中的12个元素时,你会在最终温度期间得到一个数组越界异常,因为在month
中那个位置没有对应的enter。
要解决此问题,只需确保 month
和 temperature
大小相同:
String [] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec" };