0

我是这个很棒的地方的新手。我从这个网站得到了几次帮助。我已经看到了很多关于我之前讨论过的问题的答案,但是我在使用 FileReader 计算字符数时遇到了问题。它正在使用扫描仪工作。这是我尝试过的:

class CountCharacter
{
public static void main(String args[]) throws IOException
{
    File f = new File("hello.txt");
    int charCount=0;
    String c;
    //int lineCount=0;
    if(!f.exists())
    {
        f.createNewFile();
    }
     BufferedReader br = new BufferedReader(new FileReader(f));

while ( (c=br.readLine()) != null) {
String s = br.readLine();
charCount = s.length()-1;
charCount++;


}
System.out.println("NO OF LINE IN THE FILE, NAMED " +f.getName()+ " IS " +charCount);
}
}`
4

1 回答 1

0

在我看来,每次通过循环时,都将 charCount 分配为循环迭代所关注的行的长度。即而不是 charCount = s.Length() -1; 尝试 charCount = charCount + s.Length();

编辑:

如果您说的文件内容为“ onlyOneLine

然后,当您第一次点击while检查时,br.readLine()BufferredReader读取第一行,但在while's 代码块期间br.readLine()再次调用,这会将 推进BufferredReader到文档的第二行,这将返回nullnull分配给s,然后调用length(),然后抛出 NPE 。

试试这个 while 块

while ( (c=br.readLine()) != null) { charCount = charCount + c.Length(); }

于 2013-11-13T19:31:23.547 回答