HashMap containsKey()找不到我放置的String键.字符串键的值来自于读取文本文件 [英] HashMap containsKey() cannot find the String key I have put. The String key's value is from reading a text file

查看:297
本文介绍了HashMap containsKey()找不到我放置的String键.字符串键的值来自于读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我定义了如下的哈希图:

In my program, I have defined a hashmap as follows:

HashMap<String, Integer> dictionary = new  HashMap<String, Integer>();

我必须从文本文件中读取内容,并将读取的第一个单词(即"whoo",BTW)作为字符串键放入哈希表,并以1作为值.我还将另一个键为虚拟"且值为2的值添加到哈希图中

I have to read from a text file, and put the first word I read (which is "whoo", BTW) as a String key to my hashmap, with 1 as a value. I also put another one with a key of "dummy" and value of 2 to the hashmap

try{
    File f = new File("test.txt");
    Scanner sc = new Scanner(f);
    String word = "";

     word = sc.next();

     dictionary.put(word, 1);
     dictionary.put("dummy", 2); 

     System.out.println("contains whoo as key: " + dictionary.containsKey("whoo")); 
     System.out.println("contains dummy as value: " + dictionary.containsKey("dummy")); 

 }
 catch(Exception e){
     System.out.println("error");
 }

现在我的问题是无法从哈希图的键中找到我从文本文件中读取的String键"whoo".另一方面,可以直接在哈希图的键中找到我作为字符串键直接放置的虚拟".

now my problem is that "whoo", the String key that I have read from my text file, cannot be found from the hashmap's keys. On the other hand, the "dummy" that I directly put as a String key can be found in the hashmap's keys.

我需要一种能够使containsKey()找到"whoo"的方法,因为我的程序依赖于文件读取,并使用单词作为哈希映射的String键读取.谢谢!

I need a way to be able to make containsKey() find "whoo" because my program relies on file reading and using the words read as String keys to the hashmap. Thank you!

这是我正在阅读的文本文件的内容:

this are the contents of the text file I'm reading:

我做了你们大多数人的建议,并尝试首先打印出单词的值

I did what most of you suggested and tried to print out the value of word first

System.out.println("word read is: " + word);

还添加了另一种检查,以查看我的哈希映射包含哪些键

And also added another kind of check to see what keys do my hashmap contain

Set keys = dictionary.keySet();

for (Iterator i = keys.iterator(); i.hasNext();){
    String key = (String) i.next();
    System.out.println("key found in the hashmap: " + key);

}

以下是输出:

即使String单词包含"whoo",甚至在键集中也可以找到,但是containsKey()仍然给我一个错误

Even though the String word contains "whoo", and is even found in the set of keys, containsKey() still gives me a false

推荐答案

程序从文件读取时看起来很直接,将结果输出为true.检查是否有空格,逗号或大小写.我相信这可能是问题所在.

The program looks pretty straight forward to output the result as true while reading from the file. Check for whitespaces, commas or case used. I believe that might be the issue.

正如其他人所建议的那样,使用调试器并打印出内容肯定会帮助您找到根本原因.

As suggested by others, using a debugger and printing out the contents would definitely help you track down the root cause.

这篇关于HashMap containsKey()找不到我放置的String键.字符串键的值来自于读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆