有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java修复NullPointerException

我正在编写代码来读取文本文件并计算文本文件中的所有单词。但是在while循环中,字符串数组得到一个NullPointerException。我有点理解,这意味着物体没有被指向或沿着这些线,但我不知道如何修复它

public class W273 {
    public static void main(String[] args) throws IOException {
        while (JPL.test()) {
            String fileName = "phillip.txt";
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            String line = in.readLine();
            String[] words = line.split(" ");
            int count = 0;
            String loop;
            while (in != null) {
                // move this line
                words = line.split(" ");

                for (int i = 0; i < words.length; i++) {
                    loop = words[i]; // NullPointerException here
                    count++;
                }

                line = in.readLine();
            }
            in.close();
            System.out.print(count);
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    I kinda understand that it means the object is not being pointed to or something along those lines but i cant figure out how to fix it.

    这根本不是这个意思。这意味着您在指向null而不是对象的引用上使用了点运算符(即,这里根本没有对象)

    words = line.split(" ");
    

    line为null,因此调用line。拆分导致空指针异常

    if(line!=null)
    {
        words = line.split(" ");
    }
    

    最终的原因是你的while循环

    while (in != null) {
    

    应该是

     while ((line=in.readLine()) != null) {
    

    也就是说,循环直到第一次读取空行

  2. # 2 楼答案

    您的程序可能需要一些重组。以下是我可能的做法:

    最小化字段声明。您不需要linewords的初始定义

    String fileName = "phillip.txt";
    String line;
    int count = 0;
    BufferedReader in;
    

    小心溪流。当读取文件时出现异常时,您应处理:

    try {
        in = new BufferedReader(new FileReader(fileName));
    

    接下来,赋值line,并检查赋值运算符的结果是否为null。当文件中没有更多行时,测试将失败,循环将退出

        while ((line = in.readLine()) != null) {
    

    您可以在一行中增加count。您似乎没有对loopwords做任何事情,所以现在我在这个示例中省略了这一点

            count += line.split(" ").length;
        }
    

    关闭缓冲读取器(无论发生什么!)然后退出

    } finally {
        if (in != null)
            in.close();
    }
    System.out.print(count);