【问题标题】:whole text file to string and count (nullpointerexception error) [duplicate]整个文本文件到字符串和计数(nullpointerexception 错误)[重复]
【发布时间】:2017-05-18 09:48:36
【问题描述】:

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

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

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


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

请写下文本名称:缓冲区

文本文件:

你好,我的名字是 suat

你好

你好

写出关键词: 嗨

线程“主”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\8.2\executor-sn-ps\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 );



    }

【问题讨论】:

  • 发布异常消息
  • 使用单个 readLine() 是什么意思?您的意思是不使用 while 循环吗?
  • 是的,br.readLine();我使用单行并使用程序并且程序有效。

标签: java while-loop nullpointerexception java.util.scanner bufferedreader


【解决方案1】:

您在 while 条件下为“dizi”赋值,所以它每次都被覆盖。当有东西要读时,'dizi' 有一个值并在 while 循环中打印出来。

当没有其他东西可以读取 'dizi' 时,则具有 null 值。因此,当您稍后调用“dizi.toLowerCase()”时,会出现空指针异常。

要解决此问题,您需要使用 List 跟踪所有读取的 dizi 或将它们附加到另一个 String。

【讨论】:

  • 我明白这个问题,但我要如何解决它?我可以使用字符串 [] 或 ArrayList 来解决这个问题吗?
  • 是的,这是一种方法。
猜你喜欢
  • 1970-01-01
  • 2016-11-25
  • 2011-04-20
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多