继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

整理你杂乱单词的必备代码干货

果果爱吃苹果
关注TA
已关注
手记 15
粉丝 78
获赞 3191

废话不多说,直接上代码,整理你杂乱单词的必备干货

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("成功");
    }
}
打开App,阅读手记
22人推荐
发表评论
随时随地看视频慕课网APP

热门评论


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



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


不错的代码,复习了一下排序。,。。

查看全部评论