我写的一个小程序,不知道为什么老是抛出
数组越界的异常,请各位高手指正.
import java.lang.*;
public class ArrayTest{
public static void main(String[] args)throws
ArrayIndexOutOfBoundsException{
int[] array=new int[]{1,2,6,7,5,2,8,4,6,7,9,11,5,3};
boolean change=true;
for(int i=1;i<=array.length&&change;i++){
change=false;
for(int j=i;j<=array.length-i;j++){
int temp;
if(array[j]>array[j+1]){
temp=array[j];array[j]=array[j+1];array[j+1]=temp;
change=true;
}
}
}System.out.println("最大值为:"+array[array.length]);
System.out.println("最小值为:"+array[1]);
float average;
int sum=0;
for(int i=1;i<=array.length;i++){
sum+=array[i];
}
average=sum/array.length;
System.out.println("平均值为:"+average);
System.out.println("和为:"+sum);
}}
------解决方案--------------------下标从0开始,到Array.length-1结束
你的引用有问题了
Java code
public class Overloading {
public static void main(String[] args)
throws ArrayIndexOutOfBoundsException {
int[] array = new int[] { 1, 2, 6, 7, 5, 2, 8, 4, 6, 7, 9, 11, 5, 3 };
for (int i = 0; i < array.length-1 ; i++) {
for (int j = i+1; j < array.length ; j++) {
int temp;
if (array[i] > array[i + 1]) {
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
System.out.println("最大值为:" + array[array.length-1]);
System.out.println("最小值为:" + array[0]);
float average;
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
average = sum / array.length;
System.out.println("平均值为:" + average);
System.out.println("和为:" + sum);
}
}