>**我想从用户那里获取文本,并根据搜索的单词找到文本中的单词数。BufferedReader 将 readLine 方法设置为 while 获取所有行,但程序给出空指针异常错误.
当我使用单个阅读行时,该程序运行良好。
我认为问题出在 while 循环中,但我不明白问题。
请写路径:C:\用户\灵魂收集器\桌面\八子大隈
请写下文本名称:缓冲区
文本文件:
嗨,你好,我的名字是苏特
嗨,你好
你好
写关键词:你好
线程"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\8.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("nnn Total Count of Words : " + toplamkelime );
}
你在 while 条件内为"dizi"赋值,所以它每次都被覆盖。当有内容要读取时,"dizi"有一个值,并在 while 循环中打印。
当没有其他内容可以读"笛子"时,则具有空值。因此,当您稍后调用"dizi.toLowerCase(("时,会出现空指针异常。
要解决此问题,您需要使用 List 跟踪所有已读的 dizi 或将它们附加到另一个字符串中。