【问题标题】:NullPointerException when writing to an initialized array from text document in Java从 Java 中的文本文档写入初始化数组时出现 NullPointerException
【发布时间】:2015-10-03 11:23:18
【问题描述】:

正如标题所说,我在list[i].setName(name); 收到 NullPointerException,但我不知道为什么。学生包含姓氏和分数。 data.txt 的格式为第一行:条目数量 第二行:名称(空格)分数,第三,第四等相同。 Java 和 Stack Overflow 上的新手,所以请让我知道我应该提供哪些其他细节。有问题的方法如下:

        public static Student [] readListFromFile() {
        Scanner s = new Scanner("data.txt");
        File fileName;
        boolean weGood = false;
        while (weGood == false) {
            System.out.println("Please enter the file name:");
            fileName = new File(getInput()); //user can input their own filename

                try {
                    s = new Scanner(fileName);
                    weGood = true;
                } catch (FileNotFoundException e) {
                    System.out.println("File not found, please try again");
                }
            }
        int listlength = Integer.parseInt(s.nextLine());
        Student [] list = new Student[listlength];
        for (int i = 0; i < list.length && s.hasNext() == true; i++) {
            String name = s.next();
            Double score = Double.parseDouble(s.next());
            list[i].setName(name); 
            list[i].setScore(score);
        }
        return list;
    }

【问题讨论】:

标签: java arrays eclipse nullpointerexception


【解决方案1】:

当你创建一个数组时

Student [] list = new Student[listlength];

那么所有数组元素最初都是null。 因此list[i].setName(name); 会抛出 NullPointerException。

您需要在使用数组元素之前对其进行初始化,例如

Student [] list = new Student[listlength];
for (int i = 0; i < list.length && s.hasNext() == true; i++) {
     list[i] = new Student();
     ...

【讨论】:

    【解决方案2】:

    是的,您需要在使用它们之前初始化数组元素。

    Student[] list = new Student[listLength];
    for(int i=0;i<list.length && s.hasNext() == true;i++){
     if(list[i] != null){
       list[i] = new Student();
     .....
     }
     }
    

    在使用任何对象(比如它是一个集合、字符串等)之前执行 Null 检查是一个好习惯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      相关资源
      最近更新 更多