看到别人帖子里的一道面试题, 挺有趣的, 自己写出来和大家交流下.
D盘中有一文件a.txt, 内容有字母和数字, 用户输入密码"heima"可读取文件内容, 统计出每个字母出现的次数,按照"a:1个 b:2个"的格式打印出来.
package test;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class test6 {
public static void main(String[] args) throws IOException{
//获取用户输入的密码
Scanner scan = new Scanner(System.in);
String str = null;
while((str = scan.nextLine()) != null){
//密码正确则读取文件
if("heima".equals(str)){
readFile();
break;
}else{
System.out.println("请重新输入密码");
}
}
}
public static void readFile() throws IOException{
TreeMap<Character,Integer> m = new TreeMap<Character,Integer>();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\a.txt"));
int by = 0;
while((by=bis.read()) != -1){
//判断是否为字母,排除数字和符号
if((by >= 'a' && by <='z') || (by >= 'A' && by <= 'Z')){
//System.out.print((char)by);
//如果Map中没有这个键,则初始化这个键的值为1
if(!m.containsKey((char)by)){
m.put((char)by, 1);
}else{
//如果存在,则值加1
m.put((char)by, m.get((char)by) + 1);
}
}
}
//按格式输出统计数据.
Set<Entry<Character, Integer>> set = m.entrySet();
Iterator<Entry<Character, Integer>> it = set.iterator();
while(it.hasNext()){
Entry<Character,Integer> e = it.next();
System.out.print(e.getKey() + ":" + e.getValue() + "个\t");
}
}
}
|
|