【问题标题】:FileIO - Exception in thread "main" NullPointerExceptionFileIO - 线程“主”NullPointerException 中的异常
【发布时间】:2013-05-06 00:36:06
【问题描述】:

当我运行 main 方法时,不断弹出以下内容:

Exception in thread "main" java.lang.NullPointerException 

我检查了我的代码,但找不到任何未初始化的变量。有人可以帮帮我吗?

import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;


public class FileIO 
{
public static ArrayList<Person> readData(String fileName)
{
    ArrayList<Person> personList = new ArrayList<Person>();
    int index = -1;
    try
    {
        File file = new File(fileName);
        Scanner reader = new Scanner(file);
        String s;
        Person p = null;
        boolean addressActive = false;
        while (reader.hasNext())
        {
            s = reader.nextLine();
            Scanner line = new Scanner(s);
            String cmd;

            if(line.hasNext())
            {
                cmd = line.next();

                if(cmd.equalsIgnoreCase("name"))
                {
                    index++;
                    p = new Person();
                    p.setName(line.nextLine());
                    personList.add(index,p);
                    addressActive = false;
                }

                else if(cmd.equalsIgnoreCase("birthday"))
                {
                    if(line.hasNext())
                    {
                        p.setBirthday(line.nextLine());
                        personList.set(index, p);
                    }
                    addressActive = false;

                }

                else if(cmd.equalsIgnoreCase("phone"))
                {
                    if(line.hasNext())
                    {
                        p.setPhone(line.nextLine());
                        personList.set(index, p);
                    }
                    addressActive = false;
                }

                else if(cmd.equalsIgnoreCase("email"))
                {
                    if(line.hasNext())
                    {
                        p.setEmail(line.nextLine());
                        personList.set(index, p);
                    }
                    addressActive = false;
                }

                else if(cmd.equalsIgnoreCase("address"))
                {
                    p.setAddress(line.nextLine());
                    personList.set(index, p);
                    addressActive = true;
                }

                else if(addressActive)
                {
                    String address = p.getAddress() + " " + s;
                    p.setAddress(address);
                    personList.set(index, p);
                }

                else
                    System.out.println("Error: no command" +s);
            }


        }
        reader.close(); 
        return personList;
    }
    catch(Exception e)
    {
        System.out.println("Error");
        return null;
    }

}
}

import java.util.ArrayList;


public class Test {

public static void main(String[] args) {

ArrayList<Person> person1 = FileIO.readData("C:/Users/phoenix/Desktopsample_phonebook1.txt");


System.out.println(person1.size());

}
}

看来我没有做任何更改,问题刚刚解决!我真的不知道为什么!!!!!我花了 3 个小时才找到问题,但就在一秒钟内,它就被修复了,而且没有让我知道发生了什么。! 不管怎样,谢谢你们的好意帮助~~

【问题讨论】:

  • 异常带有行号。在你的 catch 子句中添加 e.printStackTrace()。
  • 根据您的文件,p 很可能为空。
  • 实际上,您将通过删除隐藏它的行来获得堆栈跟踪。取出你的 Try/catch 块,因为你最好不要它。
  • 如果第一个命令不是“名称”,p 可能为空。堆栈跟踪肯定会告诉我们。
  • 请向我们展示整个错误信息。不仅是Exception in thread "main" java.lang.NullPointerException,还包括所有后续行。

标签: java file-io io nullpointerexception


【解决方案1】:

你的空对象

很可能,您的文件包含不等于name 的令牌。在这种情况下,因为p 仅在第一个if block 中实例化,所以您将从中获得NullPointerException

忽略设计缺陷,我注意到Person 有一个无参数构造函数。在这种情况下,将该实例移到开头并没有什么坏处。

Person p = new Person();

// Resume if else tree.

另一个潜在问题

在同样的场景中,如果你没有先得到“name”,你将尝试在索引-1 存储一个值,因为这个实例化:

int index = -1;

如何使用 e.printStackTrace()

在你的catch 子句中,你有这个:

catch(Exception e)
{
    System.out.println("Error");
    return null;
}

只需简单地将代码替换为:

catch(Exception e)
{
    e.printStackTrace();
}

【讨论】:

  • int index = -1 表示。当程序读取文件时,它读取“名称”。索引号将加 1 等于 0 表示 arraylist 中的第一个索引,然后我创建新对象
  • “名字”总是排在第一位吗?
【解决方案2】:

你只创建一个你有“名字”的人。如果您首先运行任何其他代码,您将获得 NPE。您的代码所做的很可能取决于您提供的输入。 (这很危险)

【讨论】:

    【解决方案3】:

    你应该初始化pPerson p 开头是 null。仅当 cmdname 时,您才创建 Person 对象。除此之外,您正在尝试访问一个空引用,这会导致 NullPointerException 因此,您可能希望在开始时初始化 p 而不是将其设置为 null。你可以在这里做:

    try
    {
        File file = new File(fileName);
        Scanner reader = new Scanner(file);
        String s;
        Person p = new Person();  // Initialize Person object
        boolean addressActive = false;
        while (reader.hasNext())
    

    编辑:

    如果仍然无法摆脱异常,请使用 catch 块中的 printStacktrace 方法,如下所示:

    catch(Exception e)
    {
        e.printStackTrace();
        System.out.println("Error");
        return null;
    }
    

    【讨论】:

    • @user2372861,那么你应该在你的 catch 块中使用e.printStacktrace(); 来查找发生 NPE 的确切位置。
    • 如何使用 e.printStacktrace()?我是一个新的学习者..你能帮忙吗?
    猜你喜欢
    • 2016-07-22
    • 2013-02-17
    • 2013-12-20
    • 1970-01-01
    • 2014-03-31
    • 2013-05-06
    • 2017-11-12
    • 2015-01-17
    • 2011-04-13
    相关资源
    最近更新 更多