废话不多说,直接上代码,整理你杂乱单词的必备干货
package com.hp.word;
import java.io.*;
import java.util.TreeMap;
import java.util.Map;
/**
* 排序单词
*
* @author Administrator
*资料: http://wenda.so.com/u/1901333518
*/
public class Sort2 {
// 定义一个Treemap集合
private static TreeMap<String, Integer> words = new TreeMap<String, Integer>(
String.CASE_INSENSITIVE_ORDER);
// String.CASE_INSENSITIVE_ORDER 忽略大小写
/**
* 单词排序并且计算重复
*
* @throws IOException
*/
private static void sort() throws IOException {
File f = new File("e:\\word.txt");
// 装饰模式
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f)));
// 单词
String word = null;
// 如果读取的这一行不为空的话
while ((word = reader.readLine()) != null) {
//判断是否存在键所对应的值,即判断是否有重复单词
if (words.containsKey(word))
words.put(word, words.get(word) + 1);
else
words.put(word, 1);
}
reader.close();
//排序后写入
outFile(f);
}
/**
* 重新写入文件,并且计算值
* @param f
* @throws FileNotFoundException
* @throws IOException
*/
private static void outFile(File f) throws FileNotFoundException,
IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f)));
for (Map.Entry<String, Integer> item : words.entrySet()) {
writer.write(item.getKey() + "\t" + judge(item.getValue()));
writer.newLine();
}
writer.close();
}
/**
* 判断次数是否大于2
* @param number
* @return
*/
public static String judge(Integer number) {
int n = number;
if (n < 2) {
return " ";
} else {
return number + "";
}
}
public static void main(String args[]) throws IOException {
sort();
System.out.println("成功");
}
}
热门评论
words.put(word, words.get(word) + 1);
報錯信息:
The operator + is undefined for the argument type(s) Object, int
for (Map.Entry item : words.entrySet()) {
報錯信息:
Multiple markers at this line
- Map.Entry is a raw type. References to generic type Map<K,V>.Entry<K,V> should be
parameterized
- Type mismatch: cann
不错的代码,复习了一下排序。,。。