从文本中读取NullPointerException

Alv*_*pik 0 java

public static void wordCounter(String target,BufferedReader source) throws IOException {
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        while(source.readLine() != null ) {
            String row = source.readLine();
            String[] separated = row.split(" ");
            for (int i=0; i< separated.length;i++) {
                separated[i] = separated[i].replaceAll("=+-!?'\".,:;", "");
            }

            for (int i=0; i< separated.length;i++) {
                if ( map.containsKey(separated[i]) ) {
                    int k = (Integer) map.get(separated[i]);
                    map.put(separated[i], (k+1));
                }
                else {
                    map.put(separated[i], 1);
                }
            }
        }

        if (map.containsKey(target)) {
            System.out.println( "Target word:" + target +
                    "\nAppears: " + map.get(otsitavSona) + " times." );
        }
        else {
            System.out.println( "Target word not found in source." );
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我创建的一种方法,用于从源读取并映射所有不同的单词,然后返回指定单词的出现次数.问题是在String[] separated = row.split(" ");我得到NullPointerException 的那一行.是什么导致这个问题,我该如何解决这个问题?

谢谢.

Mas*_*dul 5

你的while陈述不正确.您正在读取每一步的两行,其中第一行在while语句处被忽略.在文件的末尾,第二行是null,抛出NullPointerException.while声明应该是这样的

 String row;
 while((row=source.readLine()) != null ) {
  //String row = source.readLine(); -> Remove this line.
  String[] separated = row.split(" ");
  ...
 }
Run Code Online (Sandbox Code Playgroud)