[英]Why I am getting ArrayIndexOutOfBounds exception?
I am trying to making a simple program which computes the total marks of 3 students by passing the individual marks through a Constructor. 我正在尝试制作一个简单的程序,通过将单个分数传递给构造函数来计算3个学生的总分数。
class Student{
int n;
int[] total = new int[n];
Student(int x, int[] p, int[] c, int[] m){
int n = x;
for(int i = 0; i < n; i++){
total[i] = (p[i] + c[i] + m[i]);
System.out.println(total[i]);
}
}
}
class Mlist{
public static void main(String args[]){
String[] name = {"foo", "bar", "baz"};
int[] phy = {80,112,100};
int[] chem = {100,120,88};
int[] maths = {40, 68,60};
Student stud = new Student(name.length, phy, chem, maths);
}
}
Your total
array is initialized while n
is still 0, so it is an empty array. 您的total
组在n
仍为0时被初始化,因此它是一个空数组。
add 加
total = new int[x];
to your constructor. 给你的构造函数。
n & total array are instance variables according to your code.so default value n=0.then finally total array size become 0. n和total array是根据您的代码的实例变量 ,因此默认值n = 0,然后最终总数组大小变为0。
int[] total = new int[0]; //empty array
inside of constructor in your code 在代码中的构造函数内部
`int n = x;` //this not apply to total array size.so it is still an empty array.
code should be like this 代码应该像这样
class student{
student(int x, int[] p, int[] c, int[] m){
int[] total = new int[x];
for(int i = 0; i < x; i++){
total[i] = (p[i] + c[i] + m[i]);
System.out.println(total[i]);
}
}
}
class Mlist{
public static void main(String args[]){
String[] name = {"foo", "bar", "baz"};
int[] phy = {80,112,100};
int[] chem = {100,120,88};
int[] maths = {40, 68,60};
System.out.println(name.length);
student stud = new student(name.length, phy, chem, maths);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.