整个文本文件到字符串和计数(空指针异常错误)

whole text file to string and count (nullpointerexception error)

** 我想从用户那里获取文本,并根据搜索的单词找到文本中的单词数。 BufferedReader设置readLine方法用while获取所有行,但是程序报空指针异常错误 .

当我使用单个 readline 时程序运行良好。

我认为问题出在 while 循环中,但我不明白问题所在。**


请写路径:C:\Users\Soul Collector\Desktop\yazi okuma

请写下文本名称:buffer

文本文件:

你好你好我叫suat

你好

你好

写下关键词: 嗨

线程异常 "main" java.lang.NullPointerException

at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)

C:\Users\Soul Collector\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java 返回:1

构建失败(总时间:18 秒)


        if(press == 2 )
           {

        System.out.print("Please Write Path : ");
        scan.nextLine();
        path = scan.nextLine();

        System.out.print("Please Write the Name of Text : ");
        txtname = "\"+ scan.nextLine() + ".txt";

        finalpath = path + txtname;

        File dosya = new File(finalpath);
        FileReader fr = new FileReader(dosya);
        BufferedReader br = new BufferedReader(fr);
        String dizi;
        while((dizi = br.readLine()) != null){
            System.out.println(dizi);

        }
           br.close();



       /* StringTokenizer st = new StringTokenizer(dizi);

        while(st.hasMoreTokens()){
        System.out.println(st.nextToken());



    }*/ 

        String search=null;
        System.out.println("Write the key word : ");
       search = scan.nextLine();

        Scanner s = new Scanner(dizi.toLowerCase());
        while (s.hasNext()) {
       toplamkelime++;
           if (s.next().equals(search))
               kelime ++;
                  }
        System.out.println("Key Word : " + search);
        System.out.println("Count of key word : " + kelime);
        System.out.println("\n\n\n Total Count of Words : " + toplamkelime );



    }

您在 while 条件下为 'dizi' 赋值,因此每次都被覆盖。当有东西要读取时,'dizi' 有一个值并在 while 循环内打印。

当没有其他内容可读时 'dizi' 则具有 null 值。所以当你稍后调用 'dizi.toLowerCase()' 时,你会得到空指针异常。

要解决此问题,您需要使用 List 或将它们附加到另一个字符串来跟踪所有读过的笛子。