Reputation: 33
I have a ArrayList<String>
and a Hashtable<String, Double>
. So when I compare the arraylist with hash table, if the key(string) is found I want to get the value(double) and find the total value at the end when all the arraylist is compared. But it's giving score 0 always.
There is the code
ArrayList<String> Trigram = Trigrams.GenerateTrigrams(extra, 3);
// System.out.print(Trigram);
Hashtable<String, Double> map = readModleFile("Models//EnglishModel.txt");
double score = 0;
for (String temKey : Trigram) {
if (map.contains(temKey)) {
Double value = map.get(temKey);
score = score + value;
} else {
score = 0;
}
}
System.out.print(score);
Upvotes: 1
Views: 1922
Reputation: 89139
Your else
branch is always resetting the score to 0; the score will always be reset at least once unless the map contains all of the elements of the list. Simply remove the branch.
The second problem is that you are using contains
, which checks for a value being present, instead of containsKey
, which checks for the presence of a key.
for (String temKey : Trigram) {
if (map.containsKey(temKey)) {
Double value = map.get(temKey);
score = score + value;
}
}
The code can also be shortened and made more concise using getOrDefault
, which will either return the mapping associated with the key or the second argument (default value) if there is no mapping associated with the key.
for (String temKey : Trigram) {
score += map.getOrDefault(temKey, 0);
}
Upvotes: 4
Reputation: 40024
If the following does not work
System.out.println(map); // debug statement
for (String temKey : Trigram) {
System.out.println("temKey = " + "\"" + temKey + "\""); // debug statement
if (map.containsKey(temKey)) {
Double value = map.get(temKey);
score = score + value;
}
}
Then check the Trigram
list and the HashTable
to ensure the case of the Strings are the same or that they even exist. And make certain you are comparing "word" to "word" and don't have extraneous white space. So you may need to trim white space from the values. And put in some debug statements like the above.
Upvotes: 0
Reputation: 78945
There are two problems in your code:
contains
instead of containsKey
.else
block is resetting score
to 0
whenever the specified key is not found. Remove the else
block.You can also simplify your code as follows:
The following 4 lines
if (map.containsKey(temKey)) {
Double value = map.get(temKey);
score = score + value;
}
can be replaced with just one line
score += map.getOrDefault(temKey, 0);
Upvotes: 2
Reputation: 3917
Remove else
- it makes the score zero, every time the key is not present in the map
.
Upvotes: 1