A good answer might be:

indexOf returns 2


Complete Program

After playing with the test program a while to check that things work you can write the complete program:

import java.util.* ;
import java.io.*;

class Entry
{
  String name;
  String number;

  // constructor
  Entry( String n, String num )
  {
    name = n; number = num;
  }

  // methods
  public boolean equals( Object other )
  {
    return name.equals( ((Entry)other).name );
  }

  public String toString()
  {
    return "Name: " + name + " Number: " + number;
  }
 
}

class PhoneBookAp
{
  public static void main ( String[] args) throws IOException
  {
    Vector phone = new Vector( 10 );

    phone.addElement( new Entry( "Amy", "123-4567") );
    phone.addElement( new Entry( "Bob", "123-6780") );
    phone.addElement( new Entry( "Hal", "789-1234") );
    phone.addElement( new Entry( "Deb", "789-4457") );
    phone.addElement( new Entry( "Zoe", "446-0210") );

    String name;
    BufferedReader stdin = new BufferedReader(
      new InputStreamReader( System.in ) );

    System.out.print("Enter name -->");
    name = stdin.readLine().trim();

    while( !name.equals("quit" ) )
    {
      int spot = phone.indexOf( new Entry( name, "") ) ;

      if ( spot >= 0 )
        System.out.println( phone.elementAt( spot ) ) ;
      else
        System.out.println( name + " not found" ) ;

      System.out.print("Enter name -->") ;
      name = stdin.readLine().trim() ;
    }
 
  }
}

Of course, this is a small example and not a practical program. But the techniques it uses are used in many industrial-strength programs. Carefully examine:

  1. How a Vector of user-defined objects is used.
  2. How the equals() method is written.
    • It needs to override the inherited method for the indexOf() method to work.
    • Type casting must be used inside the method.
  3. Use of the indexOf() method to search the vector.
    • A "target" object is constructed for use with the indexOf() method.

You may regard all this as more bother than it is worth, since the previous "phone book" example worked fine using a plain array. But in large programs a linear arrangement of data is so common, and the operations on it are so frequent, that the Vector class is a worthwhile time saver.

QUESTION 23:

The application would be more practical if it would give the user more freedom in entering the target name. For example, the user should be able to enter all lower case or all caps. Where would you make a change to the program to allow this?