10. Write a Java program that loads names and phone numbers from a text file where the data is organized as one line per record and each field in a record are separated by a tab (\t). It takes a name or phone number as input and prints the corresponding other value from the hash table (hint: use hash tables).
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class HashTab
{
public static void main(String[] args)
{
HashTab h = new HashTab();
Hashtable<String, String>hashData = h.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n"+hashData);
h.printTheData(hashData, "vaag");
h.printTheData(hashData, "123");
h.printTheData(hashData, "----");
}
private void printTheData(Hashtable<String, String>hashData, String input)
{
String output = null;
if(hashData != null)
{
Set<String> keys = hashData.keySet();
if(keys.contains(input))
{
output = hashData.get(input);
}
else
{
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext())
{
String key = iterator.next();
String value = hashData.get(key);
if(value.equals(input))
{
output = key;
break;
}
}
}
}
System.out.println("Input given:"+input);
if(output != null)
{
System.out.println("Data found in HashTable:"+output);
}
else
{
System.out.println("Data not found in HashTable");
}
}
private Hashtable<String, String>readFromFile(String fileName)
{
Hashtable<String, String> hashData = new Hashtable<String, String>();
try
{
File f = new File("F:\\swings\\"+fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while((line = br.readLine()) != null)
{
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return hashData;
}
}
0 Comments