计算文件中的字符数

Kat*_*Kat 0 java char textinput

我正在编写一个程序,其中一个部分要求程序打印文件中有多少个字符(包括空格).我现在的代码虽然每次都返回0,但我不确定为什么它不计算字符.

public int getcharCount(Scanner textFile) {

        int count = 0;

        while(textFile.hasNext()) {
            String line = textFile.nextLine();
            for(int i=0; i < line.length(); i++)
                count++;
        }   
        return count;

    }
Run Code Online (Sandbox Code Playgroud)

编辑:我的程序的规格说我应该使用扫描仪.虽然我不确定,但我不相信它会进入for循环.当我使用相同的技术来计算文件中的行数时,它完美地工作.该代码是:

 public int getLineCount(Scanner textFile) {
    int lineCount = 0;

    while(textFile.hasNext()) {
        String line = textFile.nextLine();
        lineCount++;
    }

    return lineCount;
}
Run Code Online (Sandbox Code Playgroud)

我们不需要检查该行是否包含任何内容.如果它出现在文本文件的中间,则应将其计为一个字符.

Thi*_*ilo 6

我不知道它为什么不起作用(下面的代码不会解决它),但是

  for(int i=0; i < line.length(); i++)
            count++;
Run Code Online (Sandbox Code Playgroud)

可写得更简洁

  count += line.length();
Run Code Online (Sandbox Code Playgroud)