题目:给定文件"an_interesting_story.txt",实现以下两个功能:
① 仿照如下格式,输出文件中的行数、单词数及字符数(注意,空格、标点符号及其他特殊字符也算作字符,回车换行不算在内):
② 统计某个给定字母的出现次数。如提示用户输入某个字母,若用户输入字母"a",则返回文件中字母a的出现次数。若用户输入特殊字符,则通过异常处理,提示用户输入出错,并重新进行输入直至正常。
package package1;
import java.util.*;
import java.io.*;
class inputException extends Exception {
public inputException() {
}
public inputException(String mes) {
super(mes);
}
}
public class Practice10 {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, inputException {
// Scanner input = new Scanner(System.in);
System.out.println("请输入想要打开的文本文件:");
String txt = input.nextLine();
File file = new File(txt);
int con = 1;
display();
do {
int choice = input.nextInt();
switch (choice) {
case 1:
countCWL(file);
display();
break;
case 2:
boolean flag = true;
do {
try {
char search = inputLetter();
countLetter(file, search);
flag = false;
} catch (inputException ex) {
System.out.println(ex);
char searchNew = inputLetter();
countLetter(file, searchNew);
}
} while (flag);
display();
break;
case 0:
System.exit(0);
break;
default:
System.out.println("选择功能错误请重新选择!");
break;
}
} while (con != 0);
input.close();
}
public static void display() {
System.out.println("------ 菜 单---------------");
System.out.println("1.统计文件字符数单词数行数");
System.out.println("2.统计给定字母的出现次数");
System.out.println("0.退出");
System.out.println("---------------------------");
System.out.println("请选择:");
}
// 统计字符数单词数行数
public static void countCWL(File file) throws FileNotFoundException {
Scanner temp1 = new Scanner(file);
int cnum = 0, wnum = 0, lnum = 0;
System.out.println("File " + file.getName() + " has");
while (temp1.hasNextLine()) {
String str = temp1.nextLine();
lnum++;// 每循环一次就进行一次自增,用于统计行数
cnum += str.length();// 用于统计总字符数
}
Scanner temp2 = new Scanner(file);
while (temp2.hasNext()) {
String word = temp2.next();
wnum++;
}
temp1.close();
temp2.close();
System.out.println(cnum + " characters");
System.out.println(wnum + " words");
System.out.println(lnum + " lines");
}
// 统计给定字母的出现次数
public static void countLetter(File file, char c) throws FileNotFoundException {
Scanner temp = new Scanner(file);
int count = 0;
while (temp.hasNextLine()) {
String str = temp.nextLine();
for (int i = 0; i < str.length(); i++) {
char x = str.charAt(i);
if (x == c)
count++;
}
}
System.out.println(file.getName() + "中" + c + "的个数为:" + count);
temp.close();
}
public static char inputLetter() throws inputException {
System.out.println("请输入要查询的字符(区分大小写):");
char c = input.next().charAt(0);
if (c >= 'A' && c <= 'z') {
return c;
} else {
throw new inputException("非法字符!请重新输入:");
}
}
}
运行结果示例: