Maybe I'm just missing something, but I thought this code should work. The program never ends. It's supposed to read a text file, and combine the ASCII values of each letter of each word to come up with "total". It then divides total by the hash value to get its corresponding place in the array. After it's all said and done, I want to print the each word and hash value of the word in the array, along with the number of collisions. Would someone please help me with the problem and offer any helpful hints or solutions? Thanks!
import java.io.*;
import java.util.Scanner;
public class HashTable {
private HashObject[] hashArray;
private String word;
private HashObject hashItem;
private int arraySize;
public HashTable(int size) {
arraySize = size;
hashArray = new HashObject[arraySize];
}
public void displayTable() {
System.out.print("Table: ");
for (int j = 0; j < arraySize; j++) {
if (hashArray[j] != null)
System.out.print(hashArray[j].getValue() + " " + hashArray[j].getWord() + " ");
else
System.out.print("#");
}
System.out.println("");
}
public int hashFunction(int key) {
return key % arraySize;
}
private void insert(HashObject item){
int key = item.getValue();
int hashVal = hashFunction(key); // hash the key
// until empty cell,
while (hashArray[hashVal] != null) {
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
}
hashArray[hashVal] = item; // insert item
}
public HashObject find(int key) // find item with key
{
int hashVal = hashFunction(key); // hash the key
while (hashArray[hashVal] != null) // until empty cell,
{
if (hashArray[hashVal].getValue() == key)
return hashArray[hashVal]; // found, return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
}
return null; // can't find item
}
public void fillHashTable(String fileName) throws IOException {
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()) {
word = scan.next().toUpperCase();
int total = 0;
for(int i=0; i < word.length(); i++) {
char c = word.charAt(i);
if(Character.isLetterOrDigit(c))
total += (int)c;
if(c == '-')
total += (int)c;
if(c == '/')
total += (int)c;
hashItem = new HashObject(total, word);
insert(hashItem);
} // end for
} // end while
} // end method
}
import java.io.*;
public class HashTest {
public static void main(String[] args) throws IOException {
int size;
String file = "prog4a.dat";
size = 150;
HashTable theHashTable = new HashTable(size);
theHashTable.fillHashTable(file);
}
theHashTable.displayTable();
}
public class HashObject {
private int value;
private String word;
public HashObject(int v) {
value = v;
}
public HashObject(int v, String w) {
value = v;
word = w;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public String getWord() {
return word;
}
public void setWord(String w) {
word = w;
}
}