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

输入HashMap时出现Null Pointer Exception问题排查求助

排查HashMap相关Null Pointer Exception的原因与解决办法

嘿,我来帮你梳理下这段代码里触发空指针异常的问题,以及对应的修复方案:

核心异常原因

  • HashMap未初始化:你声明了两个静态HashMap变量 Grades 和 Instructor,但只做了变量声明,没有用 new HashMap<>() 给它们分配实际的内存空间。当你在main方法里尝试对这两个Map执行put/get这类操作时,它们的状态还是null,直接操作null对象就会抛出Null Pointer Exception。
  • 冗余的Scanner实例:你同时创建了两个绑定到System.in的Scanner对象(console和input),虽然这不会直接引发空指针,但会导致输入读取逻辑混乱,比如一个Scanner读取后,另一个可能无法正确获取剩余输入,属于潜在的bug。

具体解决办法

  • 初始化HashMap:在声明阶段或者main方法启动时,为两个HashMap完成初始化,二选一即可:
    方式一:声明时直接初始化
    static HashMap<String, Integer> Grades = new HashMap<>();
    static HashMap<String, String> Instructor = new HashMap<>();
    
    方式二:在main方法开头初始化
    public static void main(String[] args) throws IOException {
        Grades = new HashMap<>();
        Instructor = new HashMap<>();
        // 后续业务代码
    }
    
  • 合并Scanner实例:只保留一个Scanner来处理标准输入,比如删除static Scanner input = new Scanner(System.in);,全程用console来读取用户输入,避免输入流冲突。
  • 额外规范建议:Java里静态变量的命名建议遵循小驼峰规则(比如grades替代Grades,instructor替代Instructor),这样代码的可读性更符合行业规范。

修改后的示例代码

import java.util.HashMap;
import java.util.Scanner;
import java.io.*;

public class FillATable {
    static Scanner console = new Scanner(System.in);
    static String baseGrades;
    static String baseInstructor;
    static HashMap<String, Integer> grades = new HashMap<>();
    static HashMap<String, String> instructor = new HashMap<>();
    static double gpa;
    static int id;
    static String status;
    static int number;
    static File html;

    public static void main(String[] args) throws IOException {
        // 示例操作:向HashMap中存入数据
        System.out.println("请输入课程名称:");
        String courseName = console.nextLine();
        
        System.out.println("请输入该课程成绩:");
        int score = console.nextInt();
        grades.put(courseName, score);
        
        console.nextLine(); // 处理nextInt()留下的换行符
        System.out.println("请输入该课程讲师姓名:");
        String teacherName = console.nextLine();
        instructor.put(courseName, teacherName);
        
        // 验证数据读取与存储
        System.out.println("课程[" + courseName + "]的成绩:" + grades.get(courseName));
        System.out.println("课程[" + courseName + "]的讲师:" + instructor.get(courseName));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:52:41