class Item
{
private int address;
private String itemString;
public Item(String item)
{
separate(item);
}
public void separate(String string)
{
StringTokenizer st = new StringTokenizer(string);
itemString = st.nextToken();
if(st.hasMoreTokens())
{
address = Integer.parseInt(st.nextToken());
}
else
{
address = -1;
}
}
public String getKey()
{
return itemString;
}
public int getAddress()
{
return address;
}
public void illegitimize()
{
itemString = "*del";
address = -1;
}
}
class HashTable
{
private Item[] hashArray;
private int arraySize;
public HashTable(int size)
{
arraySize = size;
hashArray = new Item[arraySize];
}
public int hash(Item item)
{
String key = item.getKey();
int hashVal = 0;
for(int i=0; i<key.length(); i++)
{
int letter = key.charAt(i) - 96;
hashVal = (hashVal * 26 + letter) % arraySize;
}
return hashVal;
}
public void insert(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null &&
!(hashArray[hashVal].getKey().contains("*")))
{
hashVal++;
hashVal %= arraySize;
}
String keyAtHashVal = hashArray[hashVal].getKey();
String itemKey = item.getKey();
if(!keyAtHashVal.equals(itemKey))
{
hashArray[hashVal] = item;
System.out.println(item.getKey() + " inserted into the table at "
+ "position " + hashVal);
}
else
{
System.out.println("Error: " + item.getKey() + " already exists "
+ "at location " + hashVal);
}
}
public Item find(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null)
{
if(hashArray[hashVal].getKey().equals(item.getKey()))
{
System.out.println(item.getKey() + " found at location "
+ hashVal + " with address " + item.getAddress());
return hashArray[hashVal];
}
hashVal++;
hashVal %= arraySize;
}
System.out.println("Error: " + item.getKey() + " not found in the "
+ "table");
return null;
}
}
public class HashTableMain
{
public static void main(String[] args) throws Exception
{
File file = new File(args[0]);
Scanner input = new Scanner(file);
Item currentItem;
String currentItemsKey;
int currentItemsAddress;
HashTable table = new HashTable(50);
while(input.hasNextLine())
{
currentItem = new Item(input.nextLine());
currentItemsKey = currentItem.getKey();
currentItemsAddress = currentItem.getAddress();
if(currentItemsAddress > 0)
{
table.insert(currentItem);
}
else
{
table.find(currentItem);
}
}
}
}
标题几乎解释了它。当 insert() 方法尝试检索我从文件中提供的第一个项目的键时,我得到一个空指针。我认为这与我检索存储字符串的方式有关,但我无法确定问题所在。
文件中的记录将采用以下格式:
george
stacy 112
patrick 234
angelo 455
money 556
kim
chloe 223
如果行中有一个数字,我需要将项目散列到适当位置的数组中。如果没有数字,我需要搜索键(每行开头的字符串)。
编辑:添加查找功能。我遗漏了任何我认为你不需要帮助我的东西。如果您还需要什么,请告诉我。