有人可以帮我弄清楚我的 WhiteSpaceCounter 代码有什么问题吗?

Can someone help me figure out what is wrong with my WhiteSpaceCounter code?

我需要一个程序来计算文本文档中的空白,但它总是给我大量的空白,因为我认为 while 循环一直在重复。谁能读一读并告诉我发生了什么事?

import java.io.*;
public class WhiteSpaceCounter {
    public static void main(String[] args) throws IOException {
        File file = new File("excerpt.txt");
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader inreader = new InputStreamReader(fis);
        BufferedReader reader = new BufferedReader(inreader);
        String sentence;
        int countWords = 0, whitespaceCount = 0;
        while((sentence = reader.readLine()) != null) {
            String[] wordlist = sentence.split("\s+");
            countWords += wordlist.length;
            whitespaceCount += countWords -1;
        }
        System.out.println("The total number of whitespaces in the file is: "
                            + whitespaceCount);
}

}

如果你第一行有3个字,第二行有10个字,那么你的逻辑是

countWords (0) += 3 -> 3

countWords(3) += 10 -> 13

所以不要使用+=

countWords = wordlist.length;

你也可以使用这个

    while((sentence = reader.readLine()) != null) {
        String[] wordlist = sentence.split("\s+");
        whitespaceCount += wordlist.length-1;
    }