Java第七章作业
编写一个程序,程序实现对用户指定的文本文件中的英文字符和字符串的个数进行统计的功能,并将结果根据用户选择输出至结果文件或屏幕。
- 构建统计类,该类实现对I/O的操纵;实现对文本文件中英文字符、字符串的统计;实现对统计结果的输出。
- 构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用户的操作请求。
import java.io.*;
import java.util.Scanner;
public class FileAlphaCounter {
public static void main(String[] args) {
int c = 0;
Scanner sc = new Scanner(System.in);
String address = sc.nextLine();
String name = sc.nextLine();
FileInputStream in= null;
BufferedWriter bw = null;
try {
in = new FileInputStream(address+name);
bw = new BufferedWriter(new FileWriter(address+"Countof"+ name +".txt"));
}
catch(FileNotFoundException e){
System.out.println("未找到该文件");
}
catch(IOException error) {
System.out.println("文件创建错误");
}
try {
int num_of_num = 0;
int num_of_chara = 0;
while((c = in.read()) != -1) {
if(c >= '0' && c < '9') {
num_of_num++;
}
else if(c >= 'A' && c <='Z'|c >= 'a' && c <='z' ) {
num_of_chara++;
}
}
System.out.println("Character:" + num_of_chara);
System.out.println("Cumber:" + num_of_num + "\nDone!");
String result = "Character:" + num_of_chara;
String info = "The result of "+ address + name + " is : ";
bw.write(info);
bw.newLine();
bw.write(result);
bw.newLine();
result = "Number:" + num_of_num;
bw.write(result);
bw.flush();
}
catch(IOException error){
System.out.println("输出错误");
}
finally {
sc.close();
}
}
}