写错了
这个程序中, stu[i].number=i;//为什么报空指针错,现我须给这20个对象属性赋值,应该如何写呢,
多谢,

解决方案 »

  1.   

    感觉有点不对劲,啊,应该用list来存储这个20个对象,
    Student[] stu=new Student[20];
    这个行能通过?
      

  2.   

    用数组来保存固定长度的内容完全没问题。楼主的Student类的属性最好声明为private并提供get和set方法
    public class Stu { public static void main(String[] args) {
    Student[] stu = new Student[20];
    for(int i = 0 ; i < 20 ; i++){
    //创建一个Student对象
    Student s = new Student();
    s.setNumber(i);
    stu[i] = s;
    //打印设置后的值
    System.out.println(stu[i].getNumber());
    }
    }
    }
    class Student{
    private int number;
    private int state;
    private int score;
    public int getNumber() {
    return number;
    }
    public void setNumber(int number) {
    this.number = number;
    }
    public int getState() {
    return state;
    }
    public void setState(int state) {
    this.state = state;
    }
    public int getScore() {
    return score;
    }
    public void setScore(int score) {
    this.score = score;
    }
    }楼主只是声明了一个长度为20的Student数组,但是数组里面并没有Student对象,调用stu[i]实际上是null
      

  3.   

    new Student[20],只是创建了一个数组,数组里面的对象初始为null,所以报空指针,需要给数组中每一个对象进行new Student()初始化操作
      

  4.   


    public class B { public static void main(String[] args) {

    Student[] stu=new Student[20];
        for(int i=0;i<stu.length;i++){
         stu[i] = new Student();
         stu[i].number=i;//
        }
        
        for(Student s : stu)
         System.out.println(s.number); }
    }class Student{
    int number;
    int state;
    int score;
    }
      

  5.   

    Student[ ] 数组 是指向一个Student类型的引用 所以必须是一个Student类型的赋值
      

  6.   

    必然报空指针异常.
    每个元素都是null
    Student[] stu=new Student[20];
            for(int i=0;i<stu.length;i++){
    Student st=new Student();
    st.number=i;
              stu[i]=st;
            }
      

  7.   


    你的这种情况是访问或修改 null 对象的字段。所以报空指针错.