0
所以我正在做这个任务,并且出于某种原因,从字典中删除键的remove()方法无法正常工作。这里是我的方法:hashTable数组中的remove()方法
public boolean find(String key){
// Returns true if dictionary has the specified key and false otherwise
OpsCount++;
int FoundIndex = 0; // have to reset it for each find() call
int index = MADcomp(key); // get the location of the element we're looking for
int c = 0; // counter
while (size > c){
String e = D[index]; // gets the entry of the location of our element
if (e == null){
return false;
}
else if (e != AVAILABLE){ // if not a removed element
if (e.equals(key)){ //if the element in that cell has the same key as the element
//we're looking for
FoundIndex = index;
return true;
}
}
ProbesCount++;
index = (index + 1) % size; // goes to next cell
System.out.println("new index " + index);
c++;
}
return false; // nothing found
}
public void remove(String key) throws DictionaryException{
OpsCount++;
boolean found = find(key); //we're calling the find method and we'll have the indexOfFound
//variable updated for this element
if (found == true){
D[FoundIndex] = AVAILABLE;
//System.out.println(D[FoundIndex]);
n--;
}
else{
throw new DictionaryException("No entry with this key exists.");
}
}
和我的测试方法。
// Test 4: try to delete a nonexistent entry.
// Should throw an exception.
try {
h.remove("R6C8");
System.out.println("***Test 4 failed");
} catch (DictionaryException e) {
System.out.println(" Test 4 succeeded");
}
// Test 5: delete an actual entry.
// Should not throw an exception.
try {
h.remove("R3C1");
if (!h.find("R3C1"))
System.out.println(" Test 5 succeeded");
else System.out.println("***Test 5 failed");
} catch (DictionaryException e) {
System.out.println("***Test 5 failed");
}
我得到测试4成功,但5失败,程序不终止。我还检查了R3C1变成AVAILABLE(我把它删除的条目)。它失败了,因为它再次找到R3C1,即如果我说
if (h.find("R3C1"))
System.out.println(" Test 5 succeeded");
它成功。 感谢您的帮助!
谢谢!!花了很多时间试图找出错误大声笑 – user2962334 2014-10-27 20:58:42