破解采访19.8-为什么在创建哈希表时将else放入if-else语句中时输出错误

时间:2013-09-22 21:58:55

标签: java if-statement hashtable

关于破解访谈的19.8的问题是:设计一种方法来查找书中任何给定单词的出现频率。

本书提供的解决方案如下所示,只是我在else函数中添加了createHashtable

当我在if之后输入else语句时,我不知道为什么我得到错误的输出(输出是:1, 0, 0应该是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));
  }

}

1 个答案:

答案 0 :(得分:3)

你不需要先放置1个吗?

table.put(book[i], 1);

这里是代码

if( !table.containsKey(book[i])) {
  table.put(book[i], 0);
} 

并且是trim()在任何情况下都不会为您留下" "