-1

我有下面的方法来获取在双散列类中输入的键的值。运行后一直说有错误。

 /* Function to get value of a key */
 public int get(String key) 
 {
    int hash1 = myhash1( key );
    int hash2 = myhash2( key );

    while (table[hash1] != null && !table[hash1].key.equals(key))
    {
        hash1 += hash2;
        hash1 %= TABLE_SIZE;
    }
    return table[hash1].value;
}

首先,我必须在哈希表中插入一个新的名称和值,如果之后我有示例,则可以正常工作:

    System.out.println( "Please enter the name of the person you want to search for: " );
    System.out.println( "Value= " + ht.get(scan.next()));

但如果我有:

    System.out.println( "Please enter the name of the person you want to search for: " );
    System.out.println( "Value= " + ht.get(scan.nextLine()));

它说有一个错误。这意味着该方法不接受包含空格等的整行字符串,但它只接受单个字符串。Netbeans 说错误在于这一行:

return table[hash1].value;

谁能帮我?

4

1 回答 1

0

退出循环的条件之一是

while (table[hash1] != null

这意味着你知道 table[hash1] 可能是null,但你然后做

return table[hash1].value;

你得到一个 NullPointerException。这对于调试器来说是显而易见的。

我建议您在尝试使用它之前检查 table[hash1]

return table[hash1] == null ? null : table[hash1].value;

编写此方法的更好方法是

// don't go around forever if the hash2 is poor.
for(int i = 0; i < TABLE_SIZE; i++) {
    Entry e = table[hash1];
    if (e == null) return null;
    if (e.key.equals(key)) return e.value;
    hash1 += hash2;
    hash1 %= TABLE_SIZE;
}
// should never happen if hash2 is well chosen.
return null;
于 2013-11-29T16:44:44.213 回答