Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

java - HashMap containsKey() cannot find the String key I have put. The String key's value is from reading a text file

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

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

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");
 }

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.

what the program prints when I run the code

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!

EDIT:

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

text file

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);

}

Here is the output:

output

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Print your word variable before adding it to the dictionary. Better, add a breakpoint and debug. I expect you'll find it is not the value you think it is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...