java对象数组赋值时空指针问题

2023-01-02 00:00:00 数组 赋值 指针

今天学习java对象数组的时候遇到一个问题,在对数组元素赋值的时候出现空指针报错,经过咨询大佬后问题得到解决,现在记录一下

对于引用类型的数组,默认值为null,相当于里面是[null,null],需要执行

grade[0] = new studentMessage();

grade[1] = new studentMessage();

才可以,对于长度比较大的对象数组可以用循环遍历。

public class C1_Three_Lines {
    public static void main(String[] args){
        studentMessage huahua = new studentMessage();
        huahua.studentName = "huahua";
        huahua.setStudentNumber("3180530023");
        huahua.setStudentSex("male");
        huahua.printStudentMessage();
        studentMessage[] grade = new studentMessage[2];
        //对象数组需要提前赋值
        grade[0] = new studentMessage();
        grade[1] = new studentMessage();
        grade[0].setStudentMessage("huahua", "3180530023", "male");
        grade[1].setStudentMessage("yuanyuan", "3171448026", "female");
        grade[0].printStudentMessage();
        grade[1].printStudentMessage();
    }
}

class studentMessage{
    private String studentNumber;
    String studentName;
    private String studentSex;

    public void setStudentNumber(String studentNumber){
        this.studentNumber = studentNumber;
    }

    public String getStudentSex() {
        return studentSex;
    }

    public void setStudentSex(String studentSex) {
        String male = "male";
        String female = "female";
        if (studentSex.equals(male) || studentSex.equals(female)){
            this.studentSex = studentSex;
        }else {
            System.out.println("请输入正确的性别");
        }
    }

    public void getStudentNumber(){
        System.out.println(this.studentNumber);
    }

    public void printStudentMessage(){
        System.out.println("姓名:" + this.studentName + "学号为:" + this.studentNumber + "性别为:" + this.studentSex);
    }

    public void setStudentMessage(String studentName,String studentNumber,String studentSex){
        this.studentName = studentName;
        this.setStudentNumber(studentNumber);
        this.setStudentSex(studentSex);
    }
}
    原文作者:raojjunjie
    原文地址: https://blog.csdn.net/raojjunjie/article/details/124506164
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章