您的位置:首页 > 编程语言 > Java开发

第三周(JAVA编写的 wordcount)

2016-03-21 13:42 501 查看
import java.io.*;
public class WordCount {
public static int words=1;
public static int lines=1;
public static int chars=1;
public static void wc(InputStream f) throws IOException{
int c=0;
boolean last = false;
String nullspace =" \t\n\r";

while ((c=f.read()) !=-1 ){
chars++;                    //包括空格  换行
if (c == '\n')
{
lines++;
}
if (nullspace.indexOf(c)!=-1)
{
if(last){
words++;
}
last =false;
}
else{
last=true;
}

}

}
public static void main(String args[]){
FileInputStream f;
try{
if(args.length==0){
f=new FileInputStream("h:/test.txt");
wc(f);
}

}catch (IOException e)  //确保程序不会因出错崩溃
{
System.out.println("文件不存在!");
return;
}
if(words==1 && lines==1 && chars==1)
{
System.out.println("文件为空!");
}
else{
System.out.println(lines + "行 \n" + words + "个单词\n" +  chars + "个字符");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: