public class come { public static void main(String[] args) { int[] a={343,556,65767,34243,24}; int max=a[0]; for(int i=0;i<=a.length;i++){ if(a[i]>max){ max=a[i]; } } System.out.println(max); } }
控制台输出的错误提示:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
这种错误很像字符串索引越界,这种错误的错误信息后面部分与错误不大相关。但是,错误提示告诉我们错误的原因是数组越界了,非法的索引值是5,下面一行的错误信息提示错误发生在的第5行上
修改后:
public class come { public static void main(String[] args) { int[] a={343,556,65767,34243,24}; int max=a[0]; for(int i=0;i<a.length;i++){ if(a[i]>max){ max=a[i]; } } System.out.println(max); } }
当使用不合法的索引访问数组时会报数组越界这种错误,数组a的合法范围是[0, a.length-1];当访问这之外的索引时会报这个错。
Comments | NOTHING