java对象数组初始化空指针异常
关注:112 答案:6 mip版
解决时间 2021-01-31 08:01
提问者繁华落尽
2021-01-30 13:43
public class Test{
public static void main(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(int i=0;i<10;i++){
Student.stu[i] = new Student(id1[i],name1[i]);
}
}
}
public class Student{
private int id;
private String name;
static Student[] stu;
public Student(int i,String n){
this.id=i;
this.name=n;
}
}
最佳答案
二级知识专家風聲提筆
2021-01-30 14:47
你没有给static Student[] stu;
初始化啊
public static void main(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(int i=0;i<10;i++){
Student.stu[i] = new Student(id1[i],name1[i]);
}
}
全部回答
1楼妳説啲訫動
2021-01-30 19:51
static Student[] stu;
改成static Student[] stu= new Student[10];就好了
2楼热情烫伤我自
2021-01-30 18:49
Student这个类里的public Student(int i,String n){.....}是用来初始化的,而你这个语句Student.stu[i] = new Student(id1[i],name1[i]);明显有错,要想用Student.stu[i]必须使用结构体。你可以在Test这个类里定义Student []stu=new Student[10];然后再在for循环里进行初始化:stu[i] = new Student(id1[i],name1[i]);这样就可以了。不懂可以继续追问
3楼橙池未蓝
2021-01-30 17:47
我把你的类调正了一下,因为你的student里面的数组没有没有初始化,所以空指针了。
public class TestMain {
public static void main(String args[]) {
Student[] studentGroup = 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" };
studentGroup = new Student[name1.length];
for (int i = 0; i < 10; i++) {
studentGroup[i] = new Student(id1[i], name1[i]);
}
for (int i = 0; i < studentGroup.length; i++) {
System.out.print(studentGroup[i].getId());
System.out.println(studentGroup[i].getName());
}
}
}
public class Student {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
public Student(int i, String n) {
this.id = i;
this.name = n;
}
}
4楼相忘于江湖
2021-01-30 17:12
你创建stus数组,但他并没有实例化,在创建数组语句后你可以打印数组第一个元素,他显示为null,说明当前对象元素并没有创建成功,因此stus[i] = input.nextint()中stus[i]是不存在的
5楼看厌了山川
2021-01-30 16:09
Student.stu没有初始化
public class Test{
public static void main(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(int i=0;i<10;i++){
Student.stu[i] = new Student(id1[i],name1[i]);
}
}
}
class Student {
private int id;
private String name;
static Student[] stu;
public Student(int i,String n){
this.id=i;
this.name=n;
}
}
我要举报
如以上问答内容为低俗/色情/暴力/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
→点此我要举报以上信息!←
推荐资讯
大家都在看