为什么我的代码在线程“main”中显示异常java.lang.ArrayIndexOutOfBoundsException:2 在arraytest.main(arraytest.java:27)每当我运行它,虽然它没有显示任何红线错误? IndexOutOfBoundsException:数字根据输入的学生数量而变化.. ???
import java.util.Arrays;
import java.util.Scanner;
public class arraytest {
public static void main(String[] args) {
int i;
int sum = 0;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
int [] grades = new int [numStudents]; //the size we wanted
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
sum += grades[numStudents];
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
//print the array - for checking out everyting is ok
sum /= numStudents ;
System.out.println(sum);
}
}
答案 0 :(得分:0)
您的for循环不正确,请将其更改为:
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
sum += grades[i];
}
异常原因:在第一次迭代时,它进入for-loop而sum += grades[numStudents]
抛出异常,因为numStudents
是常量,并且它是数组的长度,数组中的实际元素是从索引0到(大小-1)。您应该使用循环变量i
。