java自定义类型数组

自定义的类型,创建数据后,为什么不能给对象赋值呢。代码如下。

public class Student {
String name;//对象的名称
public int [] Score;//成绩

}

//管理类
import java.util.*;
public class Manager {
public void input(Student [] stus){
Scanner in = new Scanner(System.in);
for (int i = 0;i <stus.length;i++){
System.out .print("请输入"+(i+1)+"个学生的姓名:");
stus[i].name = in.next();
for (int j = 0;j<stus[0].Score.length;j++){
System.out.print("请输入第"+(i+1)+"门成绩的分数:");
stus[i].Score[j] = in.nextInt();;
}
}

}

public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("请输入学生人数:");
int Sl = in.nextInt();
Student [] stus = new Student[Sl];
Manager manager = new Manager();
manager.input(stus);
}

}

你好,我看出两点问题来。
1. Student的对象都没有初始化,因为你只创建了数组对象,而数组的每个元素都为null,所以你运行的时候会抛出空指针异常。
2. 你的Student类里面的score属性,也定义成了数组类型,但是你没有对这个属性初始化,在下面给课程分数赋值的时候必然会出错。追问

Student数组的初始化该怎么表示呢,求解

追答

嗯,这么来吧,我给你写个实例,你看看能懂我的意思不。
Student[] stu = new Student[2] ;
stu[0] = new Student() ; //当然这里按照构造函数来实现
stu[1] = new Student() ;

追问

stu[0] = new Student() ; //这样是把Student的属性给stu[1]?
Student[] stu = new Student[2] ;//新造个数组后,里面带的是什么类型的属性呢?

追答

Student[] stu = new Student[2] ; //
上面这句代码只是创建了一个数组对象,这个数组你就想像成一个容易,可以放两个学生,但是我现在只是创建了这个容器,里面什么也没放,你不相信我的话,那么你可以打印一下,肯定都是null。所以就需要下面的语句,给这个数组装对象。
stu[0] = new Student() ; //当然这里按照构造函数来实现
stu[1] = new Student() ;

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-11
public class Student {
String name;//对象的名称
public int [] Score=new int[2];//成绩,这里有几个成绩写成几个,或者就传一个
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getScore() {
return Score;
}
public void setScore(int[] score) {
Score = score;
}

}
import java.util.*;
public class Manager {
public void input(Student[] stus){
Scanner in = new Scanner(System.in);
for (int i = 0;i <stus.length;i++){
System.out .println("请输入"+(i+1)+"个学生的姓名:");
stus[i].setName(in.next());
for (int j = 0;j<stus[0].Score.length;j++){
System.out.println("请输入第"+(i+1)+"门成绩的分数:");
stus[i].getScore()[j] = in.nextInt();
}
}

}

public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入学生人数:");
int Sl = in.nextInt();
Student [] stus = new Student[Sl];
for (int i = 0; i < stus.length; i++) {
stus[i]=new Student();
}
Manager manager = new Manager();
manager.input(stus);
}

}
相似回答