Java中向数组末尾添加元素报错:student[n]为null的修复求助
修复Java数组添加元素时的空指针错误
你遇到的空指针错误,核心原因是新创建的数组中所有元素默认都是null,直接调用student[n].setId()时,该位置还未初始化StudentModel对象。此外代码还有两个隐藏问题:原数组的旧数据未迁移到新数组,以及方法内修改数组引用无法同步到外部。
下面是分步修复方案:
1. 迁移原数组的旧数据
创建新数组后,必须把原数组的所有StudentModel对象复制过去,避免旧数据丢失。推荐用System.arraycopy()高效复制,也可以手动循环复制。
2. 初始化新位置的对象实例
在调用setXxx()方法前,必须先创建一个新的StudentModel对象,否则会触发空指针异常。
3. 修改方法返回值,同步外部数组
Java中数组是引用类型,但方法参数是值传递——修改方法内的数组引用不会改变外部的原数组。因此需要让方法返回新数组,外部通过接收返回值更新原数组。
4. 修正Scanner输入的换行符问题
sc.nextInt()只会读取数字,会把换行符留在输入流中,后续sc.nextLine()会直接读取空行,导致输入异常。需要在nextInt()后加一行sc.nextLine()吃掉换行符。
完整修复代码
// 原数组定义 StudentModel[] student = new StudentModel[] { new StudentModel(1, "Kanha", "Vong", "Female", "09/09/2000", "Siem Reap", "016663332"), new StudentModel(2, "Echrysa", "Chhy", "Male", "01/20/2000", "Pursat", "097222444"), new StudentModel(3, "Sopheak", "Chok", "female", "29/06/2005", "Battambang", "096565544"), new StudentModel(4, "Sakda", "Heang", "Male", "04/12/2001", "Banteay Meanchey", "097889900"), new StudentModel(5, "TongHan", "Khy", "Male", "03/06/2002", "Pursat", "0976543201"), new StudentModel(6, "Seyma", "Hor", "Female", "27/08/2004", "Battambang", "015765456") }; // 修改后的插入方法,返回新数组 public StudentModel[] insertStudent(StudentModel[] student) { int n = student.length; // 创建长度+1的新数组 StudentModel[] newStudentArray = new StudentModel[n + 1]; // 复制原数组的所有元素到新数组 System.arraycopy(student, 0, newStudentArray, 0, n); Scanner sc = new Scanner(System.in); System.out.print("Enter Student ID:"); int id = sc.nextInt(); // 吃掉nextInt()遗留的换行符 sc.nextLine(); System.out.print("Enter First Name:"); String firstName = sc.nextLine(); // 其他字段输入逻辑... // 初始化新位置的StudentModel对象(如果有全参构造可以直接用) newStudentArray[n] = new StudentModel(id, firstName, /* 其他字段参数 */); // 如果只有无参构造,就先创建对象再调用set方法: // newStudentArray[n] = new StudentModel(); // newStudentArray[n].setId(id); // newStudentArray[n].setFirstName(firstName); return newStudentArray; } // 调用方法时接收返回值,更新原数组 student = insertStudent(student);
内容的提问来源于stack exchange,提问作者Dan Chheng
相关产品推荐
相关产品推荐

