java编写一段程序,把一段英文字符写入data.txt文件中,然后再从文件中读取第一行数据,并统
java编写一段程序,把一段英文字符写入data.txt文件中,然后再从文件中读取第一行数据,并统计各个字符出现的次数...
java编写一段程序,把一段英文字符写入data.txt文件中,然后再从文件中读取第一行数据,并统计各个字符出现的次数
展开
2个回答
展开全部
import java.io.*;
import java.util.*;
public class Egg{
public static void main(String[] args) throws Exception{
FileWriter fw = new FileWriter("data.txt");
String word = "Look Boddy, U got work harder and put yourself into your deck ,one you learned the heart of the cards ,i can guarantee that you win.";
fw.write(word);
fw.flush();
fw.close();
Scanner scan = new Scanner(new File("data.txt"));
String str = "";
if(scan.hasNextLine()){
str = scan.nextLine();
}
scan.close();
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < str.length(); i++){
String s = str.charAt(i) + "";
if(null == map.get(s)){
map.put(s, 1);
}else{
int x = map.get(s);
map.put(s, x + 1);
}
}
System.out.println(map);
}
}
2015-12-09
展开全部
/**
* 将一段话写入一个文本
* @param args
* @throws IOException
*/
public static void writeText(String path,String words) throws IOException{
FileWriter fw = new FileWriter(path);
fw.append(words);
fw.close();
}
/**
* 读取一个文本的第一行
* @param args
* @throws IOException
*/
public static String readFirstLine(String path) throws IOException{
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
return br.readLine();
}
/**
* 统计字符串中每个字符出现的次数
* @param args
*/
public void getTotal(String str){
Map<String, Integer> maps = new HashMap<String, Integer>();
for(int i = 0; i < str.length(); i++) {
String temp = str.substring(i, i + 1);
Integer count = maps.get(temp);
if(count == null) {
count = 1;
} else {
count++;
}
maps.put(temp, count);
}
for(String key : maps.keySet()) {
System.out.println(key + "出现的次数为" + maps.get(key));
}
//得出最小次数的字母
Integer minCount = null;
for(String key : maps.keySet()) {
if(minCount == null || maps.get(key) < minCount) {
minCount = maps.get(key);
}
}
//得到最小的字母
Character minChar = null;
for(String key : maps.keySet()) {
if((int)maps.get(key) == minCount) {
if(minChar == null || key.charAt(0) < minChar) {
minChar = key.charAt(0);
}
}
}
System.out.println("结果是:字母 " + minChar + " 次数最少,只有:" + minCount);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询