home *** CD-ROM | disk | FTP | other *** search
Java Source | 1998-12-14 | 2.4 KB | 83 lines |
- import java.io.*;
- import java.util.StringTokenizer;
-
- /*
- * Phone.class implements a simple phone book with fuzzy
- * name lookup. The phone book file could be created with a
- * text editor or a spreadsheet saved as tab-delimited text.
- */
- class Phone {
-
- public static void main (String args[])
- {
- String buf;
- FileInputStream fs=null;
-
- if (args.length != 1) {
- System.out.println ("usage: java Phone <name>");
- System.exit (1);
- }
-
- /*
- * PhoneBook.txt is the name of the phone book file.
- */
- try {
- fs = new FileInputStream ("PhoneBook.txt");
- } catch (Exception e) {
- System.out.println ("Unable to open PhoneBook.txt");
- System.exit (1);
- }
- BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
- while (true) {
- try {
- buf = ds.readLine ();
- if (buf == null) break;
- } catch (IOException e) {
- System.out.println ("Exception caught reading file.");
- break;
- }
-
- /*
- * Create a new StringTokenizer for each line read
- * Explicitly specify the delimiters as both colons and tabs
- */
- StringTokenizer st = new StringTokenizer(buf, ":\t");
-
- String name = st.nextToken ();
- if (contains (name, args[0])) {
- System.out.println (name);
- System.out.println (st.nextToken ());
- System.out.println (st.nextToken () + "\n");
- }
- }
- try {
- fs.close ();
- } catch (IOException e) {
- System.out.println ("Exception caught closing file.");
- }
- }
-
- /*
- * contains method is a fuzzy string compare that returns true
- * if either string is completely contained in the other one
- * String s1, s2 two strings to compare
- */
- static boolean contains (String s1, String s2) {
-
- int i;
- int l1 = s1.length ();
- int l2 = s2.length ();
-
- if (l1 < l2) {
- for (i=0; i<=l2-l1; i+=1)
- if (s1.regionMatches (true, 0, s2, i, l1))
- return true;
- }
- for (i=0; i<=l1-l2; i+=1)
- if (s2.regionMatches (true, 0, s1, i, l2))
- return true;
-
- return false;
- }
- }
-