Java运行报NullPointerException空指针错误,该如何排查修复?
问题原因分析
- 空指针异常触发有两个核心原因:
- 你执行
Student[] icsClass = new Student[MAX];时,仅创建了一个可存储Student类型对象的数组,数组内每个位置默认值都是null,没有实例化Student对象就直接调用setXxx方法,直接触发空指针。 - 你先执行了
counter = counter + 1再用counter作为数组下标取值,假设你的MAX是10,数组合法下标范围是0~9,当counter累加到10时访问icsClass[counter]已经超出数组边界,该位置本身也是null。
- 你执行
- 额外逻辑问题:你当前代码仅在
counter == MAX的时候才会把当前输入的学生信息存入数组,前面循环过程中输入的前9个学生数据全部没有存入数组,不符合存10个学生信息的初始需求。
修复方案
- 调整counter的累加逻辑,确认信息无误后再累加,直接用当前counter作为数组下标
- 每输入完一个学生的信息确认无误后,直接将已经实例化完成的
person对象赋值给数组对应位置即可,不需要逐个调用set方法复制属性 - 去掉
counter == MAX的判断,每个学生输入完都可以确认是否正确,输入错误可以重新录入
修复后代码
public static void main(String[] args) { // 需提前定义常量:MAX=10、MIN_YEAR=1895、MAX_YEAR=2021、MIN_MONTH=1、MAX_MONTH=12、MIN_DAY=1、MAX_DAY=31 Student[] icsClass = new Student[MAX]; Scanner s = new Scanner(System.in); int counter = 0; int year; int month; int day; System.out.println("This program will store 10 student's information."); System.out.println("Do you want to continue? (Yes/No)"); String a = s.next(); if (a.equalsIgnoreCase("Yes")) { while (counter < MAX) { Student person = new Student(); System.out.println("===== 输入第" + (counter+1) + "个学生信息 ====="); System.out.println("Please enter your first name:"); person.setfName(s.next()); System.out.println("Please enter your last name:"); person.setlName(s.next()); System.out.println("Please enter your year of birth:"); year = s.nextInt(); while ((year < MIN_YEAR) || (year > MAX_YEAR)) { System.out.println("Error: Year of birth must be between 1895 and 2021"); System.out.println("Please re-enter your year of birth:"); year = s.nextInt(); } person.setYear(year); System.out.println("Please enter your month of birth:"); month = s.nextInt(); while ((month < MIN_MONTH) || (month > MAX_MONTH)) { System.out.println("Error: Month of birth must be between 1 and 12"); System.out.println("Please re-enter your month of birth:"); month = s.nextInt(); } person.setMonth(month); System.out.println("Please enter your day of birth:"); day = s.nextInt(); while ((day < MIN_DAY) || (day > MAX_DAY)) { System.out.println("Error: Day of birth must be between 1 and 31"); System.out.println("Please re-enter your day of birth:"); day = s.nextInt(); } person.setDay(day); person.display(); System.out.println("Is the information above correct? (Yes/No)"); String b = s.next(); if (b.equalsIgnoreCase("Yes")) { // 直接把实例化好的person对象存入数组对应位置 icsClass[counter] = person; // 确认无误再累加计数器 counter++; } else { System.out.println("请重新输入该学生信息"); } } // 遍历输出所有学生信息 System.out.println("===== 所有学生信息如下 ====="); for (int i = 0; i < MAX; i++) { icsClass[i].display(); } } s.close(); }
内容的提问来源于stack exchange,提问作者Faruk
相关产品推荐
相关产品推荐

