/**
* Uses a hash-coded data storage method to store items
* from a file. a linked list is used as the method for
* dealing with collisions
* Uses try, catch, and finally
*/
// Josh Alberts
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
import java.util.StringTokenizer;
public class Hashing
{
Hashtable table;
final int TABLESIZE = 600;
DecimalFormat fmt = new DecimalFormat("0.00");
public Hashing()
{
table = new Hashtable(TABLESIZE);
}
public void search()
{
int idToFind;
Item location;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Id value to search for (-1 to quit) -->");
idToFind = scan.nextInt();
while(idToFind >= 0)
{
location = (Item)table.find(new Item(idToFind, 0));
if(location == null)
System.out.println("Id = "+ idToFind + " No such part in stock");
else
System.out.println("Id = "+ location.getId()+ " Inv" + location.getInv());
System.out.println();
System.out.print("Enter Id value to search for (-1 to quit) -->");
idToFind = scan.nextInt();
}
}
public void stats()
{
System.out.println("Number of Nulls: " + table.getNumberOfNulls());
System.out.println("% of Nulls: " + fmt.format(((double)table.getNumberOfNulls()/TABLESIZE)*100) + "%");
int emptySpots = table.getNumberOfNulls();
double avg = (double)table.getSize()/(table.getCapacity() - emptySpots);
System.out.println("Average list lenght: " + fmt.format(avg));
System.out.println("The longest list is: "+ table.getLongestList());
}
public void loadFile() throws IOException
{
String fileName = "file30.txt";
int id, inv;
String line=""; // declared out of try block so accessible
BufferedReader inFile = null; // in later code
FileReader fr = null;
try
{
fr = new FileReader(fileName);
inFile = new BufferedReader(fr);
line = inFile.readLine();
System.out.println ("ID \t INVENTORY");
System.out.println ("First line read " + line);
while (line != null)
{
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens())
{
id = Integer.parseInt(tokenizer.nextToken());
System.out.print(id + "\t");
inv = Integer.parseInt(tokenizer.nextToken());
System.out.println(inv );
table.add(new Item(id, inv));
}
line = inFile.readLine();
}
}
catch(NumberFormatException exception)
{
System.out.println("Error in input. Line ignored \n");
System.out.println(line);
}
catch(FileNotFoundException exception)
{
System.out.println ("The file " + fileName + " was not found \n");
}
catch(IOException exception)
{
System.out.println(exception);
}
finally
{
if (line != null)
{
inFile.close();
}
}
}
public String toString()
{
return table.toString();
}
}
/* Easier - no try, catch, finally
int howMany = 400;
for (int k = 1; k <= howMany; k++)
{
id = inFile.readInt();
inv = inFile.readInt();
table.add(new Item(id, inv));
}
*/