Java对象数组空指针异常求助:s[i]为null无法调用setName
解决对象数组的NullPointerException问题
Hey there, let's break down why you're running into that NullPointerException and fix it step by step!
问题根源
When you declare Student s[] = new Student[2];, you're only creating an array container that can hold Student objects—every position in this array starts as null by default. You haven't actually created any Student instances to put into the array yet, so calling methods like s[i].setName() will throw a null pointer error because s[i] isn't a real Student object.
On top of that, your code has a few other small issues:
- Your array length is 2, but you try to access
s[2]later—Java arrays are 0-indexed, so a length-2 array only uses indices 0 and 1 (this would cause anArrayIndexOutOfBoundsExceptiononce you fix the null issue) - You declare
int i=0;inside the do-while loop, soiresets to 0 every loop iteration—you'll keep overwriting the first array element instead of filling the rest - You don't need multiple
Scannerobjects; one is enough to handle all input, and using multiple can cause unexpected input behavior
修复方案
Here's the fixed code with explanations:
完整修复后的主类代码
import java.util.Scanner; public class Main { public static void main(String[] args) { // 调整数组长度为3,匹配录入3名学生的需求 Student s[] = new Student[3]; // 只用一个Scanner处理所有输入,避免输入冲突 Scanner scanner = new Scanner(System.in); // 将循环变量i声明在循环外,防止每次循环重置 int i = 0; // 循环录入3名学生的信息 while(i < 3) { // 关键修复:在使用数组元素前,先实例化Student对象 s[i] = new Student(); System.out.println("Enter Name"); String nameInput = scanner.nextLine(); s[i].setName(nameInput); System.out.println("Enter ID"); String IDInput = scanner.nextLine(); s[i].setId(IDInput); System.out.println("Enter Phone Number"); int phoneNumberInput = scanner.nextInt(); s[i].setPhoneNumber(phoneNumberInput); // 处理nextInt()遗留的换行符,避免下一次nextLine()读取空字符串 scanner.nextLine(); i++; } // 输出所有学生信息,索引范围为0-2 System.out.println("Name:" + s[0].getName()); System.out.println("Name:" + s[1].getName()); System.out.println("Name:" + s[2].getName()); System.out.println("ID:" + s[0].getId()); System.out.println("ID:" + s[1].getId()); System.out.println("ID:" + s[2].getId()); System.out.println("Phone:" + s[0].getPhoneNumber()); System.out.println("Phone:" + s[1].getPhoneNumber()); System.out.println("Phone:" + s[2].getPhoneNumber()); } }
核心修复点
- 实例化数组元素:每次循环先执行
s[i] = new Student();,把数组里的空位置替换为实际的Student对象,这样就能安全调用它的setter方法了 - 调整数组长度:改成
new Student[3]来匹配你要录入3名学生的需求 - 统一Scanner对象:只用一个Scanner避免输入处理混乱,同时添加
scanner.nextLine()处理nextInt()后的换行符,防止后续nextLine()读取空内容 - 修复循环变量:把
i的声明移到循环外,确保每次循环i递增,依次填充数组的每个位置
额外拓展
如果想让用户自主决定何时停止录入学生(而非固定3名),可以调整循环逻辑:比如每次录入后询问用户是否继续,根据输入决定是否退出循环。
内容的提问来源于stack exchange,提问作者Habeeb E Sadeed
相关产品推荐
相关产品推荐

