这段代码编译没问题,但是运行却报错了,可是我又看不懂这报错是什么意思。。。。代码:class ArrayTools {
private ArrayTools(){}
//遍历数组
public static void printArr(int[] arr){
System.out.print("[");
for(int x = 0;x<arr.length;x++){
if(x==arr.length-1){
System.out.print(arr[x]);
}else{
System.out.print(arr[x]+", ");
}
}
System.out.println("]");
}
//求最大元素
public static int getMax(int[] arr){
int max = arr[0];
for(int x = 1;x<arr.length;x++){
if (arr[x]>arr[max]){
max = arr[x];
}
}return max;
}
//求索引
public static int getIndex(int[] arr,int value){
int index = -1;
for (int x = 0;x<arr.length;x++ ){
if(arr[x]==value){
index = x;
break;
}
}return index;
}
}
class ArrayDemo {
public static void main(String[] args){
int[] arr = {11,44,55,22,66};
//ArrayTools at = new ArrayTools();
//at.printArr(arr);
ArrayTools.printArr(arr);
int max = ArrayTools.getMax(arr);
System.out.println(max);
int index = ArrayTools.getIndex(arr,22);
System.out.println(index);
}
}
报错:[11, 44, 55, 22, 66]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at ArrayTools.getMax(ArrayTools.java:21)
at ArrayDemo.main(ArrayDemo.java:7)
请按任意键继续...
|