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.
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:
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:
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…