问题描述:
用Java统计txt文件下的字符、单词和行的总数,
并且查询特定字母出现的次数,
如果输入不规范,则重新输入,直到输入为一个字母位置,
并且查询该字母在文件中出现的次数
代码实现:(此处文件名为“an_interesting_story.txt”)
package com.HelloWorld;
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Fileoperation{
public static void main(String[] args) throws Exception {
File file = new File("an_interesting_story.txt");
if(!file.exists()) {
System.out.println("The file is Null");
System.exit(0);
}
Scanner cin = new Scanner(file);
int charactere=0, words=0, lines=0;
while(cin.hasNext()) {
String line = cin.nextLine();
lines++;
charactere+=line.length();
String[] s = line.trim().split(" ");
words+=s.length;
//System.out.println(s.length);
}
System.out.println("File " + file + " has");
System.out.println(charactere + " charactere");
System.out.println(words + " words");
System.out.println(lines + " lines");
Scanner input = new Scanner(System.in);
Scanner cout = new Scanner(file);
System.out.print("请输入一个需要匹配文件的字母:");
boolean flag = true;
int sum=0;
while(flag) {
char ch = input.nextLine().charAt(0);
try {
is(ch);
while(cout.hasNext()) {
String line = cout.nextLine();
for(int i=0; i<line.length(); ++i)
if(line.charAt(i) == ch)
sum++;
}
System.out.println(ch + "出现的次数为: " + sum);
flag = false;
}catch(Exception e){
System.out.print("格式不正确,请重新输入: ");
}
}
}
public static void is(char ch) throws Exception{
if(!((ch>='a' && ch<='z') || (ch>='A' && ch<='Z')))
throw new Exception();
}
}