我编写了以下代码来计算不包括空格的字符数,计算字数,计算行数。但是我的代码没有显示正确的输出。
import java.io.*;
class FileCount
{
public static void main(String args[]) throws Exception
{
FileInputStream file=new FileInputStream("sample.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(file));
int i;
int countw=0,countl=0,countc=0;
do
{
i=br.read();
if((char)i==(' '))
countw++;
else if((char)i==('\n'))
countl++;
else
countc++;
}while(i!=-1);
System.out.println("Number of words:"+countw);
System.out.println("Number of lines:"+countl);
System.out.println("Number of characters:"+countc);
}
}
我的文件 sample.txt 有
hi my name is john
hey whts up
我的输出是
Number of words:6
Number of lines:2
Number of characters:26