indexOf returns 2
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:
Vector
of user-defined objects is used.equals()
method is written.
indexOf()
method to work.indexOf()
method to search the vector.
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.