java对象数组初始化空指针异常
:112回答关注:6mip版
解决时间2021-01-31 08:01
提问者充斥着繁华的街道
2021-01-30 13:43
公共类测试{
publicstaticvoidmain (string args [ ] ) {
int [ ] id1={ 1,2,3,4,5,6,7,8,9,10 };
String[] name1={'a '、' b '、' c '、' d '、' e '、' f '、' g '、' h '、' I '、' j'};
for(intI=0; i10; I ) {
sudent.stu [ I ]=new student (id1 [ I ],name1[i];
}
}
}
公共类事件{
私有Int id;
私有字符串名称;
静态稳定[ ] stu;
公共事件(inti,String n ) {
this.id=i;
this.name=n;
}
}
最佳答案
二级知识专家风声提笔
2021-01-30 14:47
你没有给静态student [ ] stu;
初始化哦
publicstaticvoidmain (string args [ ] ) {
int [ ] id1={ 1,2,3,4,5,6,7,8,9,10 };
String[] name1={'a '、' b '、' c '、' d '、' e '、' f '、' g '、' h '、' I '、' j'};
Student.stu[]=new Student[10];
for(intI=0; i10; I ) {
sudent.stu [ I ]=new student (id1 [ I ],name1[i];
}
}
全部回答
一楼你说的意思
2021-01-30 19:51
静态稳定[ ] stu;
静态student [ ] stu=new student [ 10 ]; 太好了
二楼被热情烧伤
2021-01-30 18:49
名为Student的类的公共student (inti,String n )……}用于初始化,但student.stu[I]=newstudent ) id1[I],name1[i] ); 很明显是错的。 使用Student.stu[i]必须使用结构体。 在名为Test的类中Student []stu=new Student[10]; 然后,在for循环中进行初始化。 stu[I]=newstudent(id1[I],name1[i]; 这样就可以了。 如果你不明白,可以问
三楼橙色游泳池不蓝
2021-01-30 17:47
我修改了你的班级。 因为你的student中的数组没有初始化,所以变成了空指针。
公共类测试主{
publicstaticvoidmain (string args [ ] ) {
student [ ] student组=null;
int [ ] id1={ 1,2,3,4,5,6,7,8,9,10 };
String[] name1={ 'a '、' b '、' c '、' d '、' e '、' f '、' g '、' h '、' I '、' j' };
sudent group=new student [ name1. length ];
for(intI=0; i 10; I ) {
事件组[ I ]=新事件(id1 [ I ],name1[i];
}
for(intI=0; i studentGroup.length; I ) {
system.out.print (student group [ I ].getid ();
system.out.println (student group [ I ].getname ();
}
}
}
公共类事件{
公共插入门tid
返回id;
}
公共语音设置(Intid ) {
this.id=id;
}
公共字符串getname
返回名称;
}
公共语音集名称(字符串名称) {
this.name=name;
}
私有Int id;
私有字符串名称;
公共事件(inti,String n ) {
this.id=i;
this.name=n;
}
}
四楼相被江湖遗忘
2021-01-30 17:12
你创建了stus数组,但他没有实例化。 创建数组语句后,可以打印数组的第一个元素。 他显示为null,表示当前对象元素未成功创建。 因此,stus[i]=input.nextint ) )中不存在stus[i]
五楼看厌了山川
2021-01-30 16:09
Student.stu尚未初始化
公共类测试{
publicstaticvoidmain (string args [ ] ) {
int [ ] id1={ 1,2,3,4,5,6,7,8,9,10 };
String[] name1={'a '、' b '、' c '、' d '、' e '、' f '、' g '、' h '、' I '、' j'};
Student.stu=new Student[10];
for(intI=0; i10; I ) {
sudent.stu [ I ]=new student (id1 [ I ],name1[i];
}
}
}
类student {
私有Int id;
私有字符串名称;
静态稳定[ ] stu;
公共事件(inti,String n ) {
this.id=i;
this.name=n;
}
}
我要报警
如果以上答疑内容为低俗/色情/暴力/不良/侵权信息,可以点击以下链接进行举报。 我们会做出相应的处理。 谢谢您的支持。
点击此处通报上述信息!
推荐信息
大家都在看