ArrayIndexOutOfBoundsException:0错误
问题描述:
我的数组有一个不固定的大小,因为它取决于输入模块的数量的用户输入,所以我真的不知道该怎么办,当我运行此代码并得到此错误:ArrayIndexOutOfBoundsException:0ArrayIndexOutOfBoundsException:0错误
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
//Method for input of number of modules
moduleno = Student.modno();
for (int i = 0; i < moduleno; i++) {
modulename = Student.MakingModName(i);
grade = Student.readGrade(i);
cu = Student.readCredits(i);
value = Student.GradeValue(grade);
score = Student.calculateScore(value, cu);
totalScore += score;
totalCu += cu;
GPA = Student.calculateGPA(totalCu, totalScore);
//Error occurs here.
**array[i] = new Module(modulename,grade,cu);**
a[i] = array[i].getModulename();
b[i] = array[i].getGrade();
c[i] = array[i].getCu();
Output[i] = a[i] + " " +b[i]+" " +c[i]+" ";
endoutput = endoutput + Output[i] + "\n";
}
答
语句序列:
Module[] array = new Module[moduleno];
moduleno = Student.modno();
不会奇迹般地调整先前已分配的阵列。你需要做的圆用另一种方式:
moduleno = Student.modno();
Module[] array = new Module[moduleno];
答
移动声明
moduleno = Student.modno(); // this should be the value while you initialize the array
你初始化数组之前。
答
//Add This line before initialize your array
**moduleno = Student.modno();**
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
原因: 默认情况下,您的moduleno变量包含0(零)大小,这样你所有的数组的大小也为0(零)。
而您尝试在数组中添加1个元素,但数组的大小为零,因此它会给出ArrayIndexOutBoundsException。
你在哪行中得到错误 –
数组在哪里被初始化,哪一个导致错误? –
什么是“不固定的数组大小”?看来你已经创建了零长度的数组。 – Henry