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 filed 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).
Program Code:
import java.io.*;
import java.util.*;
public class Phonebook
{
public static void main(String args[])
{
Try
{
FileInputStream fis=new FileInputStream("//home/gcet/Desktop/myfile.txt");
Scanner sc=new Scanner(fis).useDelimiter("\t");
Hashtable<String,String> ht=new Hashtable<String,String> ();
String[] strarray;
String a,str;
while(sc.hasNext())
{
a=sc.nextLine();
strarray=a.split("\t");
ht.put(strarray[0],strarray[1]);
System.out.println("hash table values are"+strarray[0]+":"+strarray[1]);
}
Scanner s=new Scanner(System.in);
System.out.println("Enter the name as given in the phone book");
str=s.next();
if(ht.containsKey(str))
{
System.out.println("phone no is"+ht.get(str));
}
else
{
System.out.println("Name is not matched");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Myfile.txt
Surya 567
Ravi 456
Sudha 678
Output:
Surya: 567
Ravi: 456
Sudha: 678
Enter the name as given in the phone book
Ravi
phone no is: 456
Enter the name as given in the phone book
Soni
Name is not matched
java.lang.ArrayIndexOutOfBoundsException: 1 this type error is occur please solve the above program
ReplyDelete