[英]containsKey method of TreeMap returns false despite that the key is already in the Map
我嘗試編寫一個計算文本文件中所有單詞的程序。 我在TreeMap中輸入了與模式匹配的任何單詞。
我通過args0
獲得的文本文件
例如,文本文件包含以下文本: The Project Gutenberg EBook of The Complete Works of William Shakespeare
來檢查,如果映像樹已經有詞,返回的條件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);
}
}
}
}
}
我已經測試了您的代碼,沒關系。 我認為您必須檢查文件編碼。
它肯定在“ UTF-8”中。 將其放入“沒有BOM的UTF-8”中,您就可以了!
編輯:如果您無法更改編碼,則可以手動進行。 看到此鏈接: http : //www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.