输入哈希映射时的空指针执行

时间:2018-04-19 00:26:57

标签: java nullpointerexception hashmap

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

 public class FillATable {
 static Scanner console = new Scanner(System.in);
 static Scanner input = new Scanner(System.in);
 static String BaseGrades;
 static String BaseInstructor;
 static HashMap<String, Integer> Grades;
 static HashMap<String, String> Instructor;
 static double GPA;
 static int ID;
 static String status;
 static int Number;
 static File html;

    public static void main(String[] args) throws IOException {
    System.out.println("Full Name ?");
    fullname = console.nextLine();

    System.out.println("Number of courses taken ?");
    Number = console.nextInt();
    System.out.println("Please input the courses taken along with the 
    respective grades ");
    for (int i = 0; i <= Number; i++) {
        Grades.put(console.next(), console.nextInt());
    }

    System.out.println("Please input the courses taken along with the 
    respective instructors");
    for (int i = 0; i < Number; i++) {
        Instructor.put(console.nextLine(), console.nextLine());
    }

    System.out.println("GPA ?");
    GPA = input.nextDouble();

    System.out.println("ID number ?");
    ID = input.nextInt();

    for (String course : Instructor.keySet()) {
        String value = Instructor.get(course);
        BaseInstructor = BaseInstructor + "( " + course + "," + value + ")";

    }
    for (String course : Grades.keySet()) {
        Integer value = Grades.get(course);
        BaseGrades = BaseGrades + "( " + course + "," + value + ")"

      }

当我进入课程并对任何想法进行评分时,我得到一个空指针异常?它似乎很直接,我必须有一些东西,但我不知道它是什么。出于我的工作目的,开头的变量应始终保持静态

1 个答案:

答案 0 :(得分:0)

在尝试与Grades交互之前,您需要在某处使用此行:

grades = new HashMap<String, Integer>();

我会在主方法的开头或第一次声明变量时把它放在正确的位置。对于尚未初始化的所有其他类级变量(如Instructor)也是如此。

这是因为您声明但未设置为初始值的任何对象的值都为null。基本上你在你编写的任何Java中声明的每个变量都是如此。

如果您尝试使用值为null的对象的方法或成员,则会得到NullPointerException

希望这有帮助!