19.8 破解面试的问题是:设计一种方法来找出书中任何给定单词的出现频率。
本书提供的解决方案如下所示,除了我else
在createHashtable
函数中添加了一个。
当我在 if 之后键入 else 语句时,我 不知道为什么会得到错误的输出(输出是:1, 0, 0
which should be )。2, 1, 1
import java.util.Hashtable;
public class Question198
{
/*create a hashtable for the strings in the book*/
public static Hashtable<String, Integer> createHashtable(String[] book) {
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
for(int i = 0; i < book.length; i++) {
book[i] = book[i].toLowerCase();
if(book[i].trim() != " ") {
if( !table.containsKey(book[i])) {
table.put(book[i], 0);
}
else{ // ?? why else is here is wrong??
table.put(book[i], table.get(book[i]) + 1);
}
}
}
return table;
}
/*get the frequency of the given word in the book*/
public static int getFrequency(Hashtable<String, Integer> table, String word) {
if( table == null || word == null) return -1;
word = word.toLowerCase();
if( table.containsKey(word)) {
return table.get(word);
}
return 0;
}
/*Test*/
public static void main(String[] args) {
String[] book1 = {"This", "is", "a", "is", "case",};
Hashtable<String, Integer> test1 = createHashtable(book1);
String word1 = "is";
String word2 = "a";
String word3 = "case";
System.out.println("Expected(2): " + getFrequency(test1, word1));
System.out.println("Expected(1): " + getFrequency(test1, word2));
System.out.println("Expected(1): " + getFrequency(test1, word3));
}
}