尽管密钥已经在Map中,但TreeMap的containsKey方法返回false

时间:2017-06-22 13:34:07

标签: java treemap containskey

我尝试编写一个计算文本文件中所有单词的程序。 我在TreeMap中添加了与模式匹配的任何单词。

我通过args0

获得的文本文件

例如,文本文件包含以下文本:The Project Gutenberg EBook of The Complete Works of William Shakespeare

检查TreeMap是否已包含该单词的条件,对于单词false的第二次出现返回The,但返回true单词of的第二次出现

我不明白为什么......
这是我的代码:

public class WordCount
{
    public static void main(String[] args)
    {
        // Charset charset = Charset.forName("UTF-8");
        // Locale locale = new Locale("en", "US");

        Path p0 = Paths.get(args[0]);
        Path p1 = Paths.get(args[1]);
        Path p2 = Paths.get(args[2]);

        Pattern pattern1 = Pattern.compile("[a-zA-Z]");
        Matcher matcher;
        Pattern pattern2 = Pattern.compile("'.");

        Map<String, Integer> alphabetical = new TreeMap<String, Integer>();

        try (BufferedReader reader = Files.newBufferedReader(p0))
        {
            String line = null;

            while ((line = reader.readLine()) != null)
            {
                // System.out.println(line);
                for (String word : line.split("\\s"))
                {
                    boolean found = false;

                    matcher = pattern1.matcher(word);
                    while (matcher.find())
                    {
                        found = true;
                    }
                    if (found)
                    {
                        boolean check = alphabetical.containsKey(word.toLowerCase());
                        if (!alphabetical.containsKey(word.toLowerCase()))
                            alphabetical.put(word.toLowerCase(), 1);
                        else
                            alphabetical.put(word.toLowerCase(), alphabetical.get(word.toLowerCase()).intValue() + 1);
                    }
                    else
                    {
                        matcher = pattern2.matcher(word);
                        while (matcher.find())
                        {
                            found = true;
                        }
                        if (found)
                        {
                            if (!alphabetical.containsKey(word.substring(1, word.length())))
                                alphabetical.put(word.substring(1, word.length()).toLowerCase(), 1);
                            else
                                alphabetical.put(word.substring(1, word.length()).toLowerCase(), alphabetical.get(word).intValue() + 1);
                        }
                    }
                }
            }
}

1 个答案:

答案 0 :(得分:0)

我已经测试了你的代码,没关系。我想你必须检查你的文件编码。

肯定是“UTF-8”。把它放在“没有BOM的UTF-8”中,你就可以了!

编辑: 如果您无法更改编码,则可以手动执行。看到这个链接: http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html

此致