You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java向Student数组存储临时数据触发NullPointerException问题求助

Java数组存储临时数据空指针异常解决方案

问题根因

  • 数组初始化时仅创建了容器,未实例化数组内的Student对象:Student iscClass[] = new Student[MAX]; 执行后数组内所有元素默认值为null,直接调用iscClass[i].setXXX()会触发空指针异常
  • 逻辑错误:全程仅实例化1个Student对象,每次输入都会覆盖上一个学生的信息,最终无法保存所有录入数据
  • 边界错误:数组下标范围为0 ~ MAX-1,代码中counter <= MAX、for (int i = 0; i <= MAX; i++)会触发数组越界异常
  • Scanner使用不规范:同时创建两个Scanner对象读取输入流,且nextInt()执行后未消费换行符,会导致后续nextLine()读取到空值

修复方案

  1. 每次录入新学生信息前新建Student对象,用户确认信息正确后直接存入数组对应位置,无需最后统一赋值
  2. 调整循环边界为< MAX,避免数组越界
  3. 统一使用单个Scanner对象,每次nextInt()后补充调用nextLine()吃掉换行符
  4. 移除冗余的correct变量逻辑,简化流程

修正后完整代码

package com.company;
import static com.company.ProjectCONSTANTS.*;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Student iscClass[] = new Student[MAX];
        int counter = 0;
        String uInput01;
        Scanner sc = new Scanner(System.in);

        System.out.println("This program will collect and store 10 people's full name and their date of birth.");
        System.out.println("Would you like to continue? (input yes or no)");
        uInput01 = sc.nextLine().toLowerCase();
        while (!uInput01.equals("yes") && !uInput01.equals("no")) {
            System.out.println("Please input yes or no: ");
            uInput01 = sc.nextLine().toLowerCase();
        }
        if (uInput01.equals("no")) {
            sc.close();
            return;
        }

        while (counter < MAX) {
            Student st = new Student();
            System.out.println("\nData for person " + (counter+1) + ":");

            // 录入姓名
            System.out.println("\nenter first name: ");
            String fNameInput = sc.nextLine();
            st.setFirstName(fNameInput);
            System.out.println("First name: " + fNameInput);

            System.out.println("\nenter last name: ");
            String lNameInput = sc.nextLine();
            st.setLastName(lNameInput);
            System.out.println("Last name: " + lNameInput);

            // 录入年份
            System.out.println("\nenter the year of birth: ");
            while (!sc.hasNextInt()) {
                System.out.println("please enter a number\nenter again: ");
                sc.next();
            }
            int yearInput = sc.nextInt();
            sc.nextLine(); // 吃掉换行符
            while (yearInput < MIN_YEAR || yearInput > MAX_YEAR) {
                System.out.println("year must be in between " + MIN_YEAR + " and " + MAX_YEAR + "\nPlease enter again: ");
                while (!sc.hasNextInt()) {
                    System.out.println("please enter a number: ");
                    sc.next();
                }
                yearInput = sc.nextInt();
                sc.nextLine();
            }
            st.setYear(yearInput);
            System.out.println("Year of birth: " + yearInput);

            // 录入月份
            System.out.println("\nenter the month of birth: ");
            while (!sc.hasNextInt()) {
                System.out.println("please enter a number\nenter again: ");
                sc.next();
            }
            int monthInput = sc.nextInt();
            sc.nextLine();
            while (monthInput < MIN_MONTH || monthInput > MAX_MONTH) {
                System.out.println("month must be in between " + MIN_MONTH + " and " + MAX_MONTH + "\nPlease enter again: ");
                while (!sc.hasNextInt()) {
                    System.out.println("please enter a number: ");
                    sc.next();
                }
                monthInput = sc.nextInt();
                sc.nextLine();
            }
            st.setMonth(monthInput);
            System.out.println("Month of birth: " + monthInput);

            // 录入日期
            System.out.println("\nenter the day of birth: ");
            while (!sc.hasNextInt()) {
                System.out.println("please enter a number\nenter again: ");
                sc.next();
            }
            int dayInput = sc.nextInt();
            sc.nextLine();
            while (dayInput < MIN_DAY || dayInput > MAX_DAY) {
                System.out.println("day must be in between " + MIN_DAY + " and " + MAX_DAY + "\nPlease enter again: ");
                while (!sc.hasNextInt()) {
                    System.out.println("please enter a number: ");
                    sc.next();
                }
                dayInput = sc.nextInt();
                sc.nextLine();
            }
            st.setDay(dayInput);
            System.out.println("Day of birth: " + dayInput);

            // 确认信息
            st.display();
            System.out.println("\nIs the data above correct? (input yes or no)");
            uInput01 = sc.nextLine().toLowerCase();
            while (!uInput01.equals("yes") && !uInput01.equals("no")) {
                System.out.println("Please input yes or no: ");
                uInput01 = sc.nextLine().toLowerCase();
            }
            if (uInput01.equals("yes")) {
                iscClass[counter] = st; // 确认无误直接存入数组对应位置
                counter++;
            } else {
                System.out.println("Let's try again!");
            }
        }

        // 打印所有已保存的学生信息验证
        System.out.println("\nAll stored student info:");
        for (int i = 0; i < counter; i++) {
            System.out.println("\nStudent " + (i+1) + ":");
            iscClass[i].display();
        }
        sc.close();
    }
}

内容的提问来源于stack exchange,提问作者ossc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:54:04