PhoneEntry[] phoneBook = new PhoneEntry[ 5 ] ;
phoneBook is an array of 5 references to phoneEntry
objects.
But so far there are no phoneEntry objects and every slot
of phoneBook is null.
Yes, you already knew that. But it is easy to forget. Here is a skeleton of the application:
class PhoneEntry
{
String name; // name of a person
String phone; // their phone number
PhoneEntry( String n, String p )
{
name = n; phone = p;
}
}
class PhoneBook
{
PhoneEntry[] phoneBook;
PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 5 ] ;
// load the phone book with data
. . . .
}
PhoneEntry search( String targetName )
{
// use linear search to find the targetName
. . . .
}
}
class PhoneBookTester
{
public static void main ( String[] args )
{
PhoneBook pb = new PhoneBook();
// search for "Violet Smith"
PhoneEntry entry =
pb.search( "Violet Smith" );
if ( entry != null )
System.out.println( entry.name +
": " + entry.phone );
else
System.out.println("Name not found" );
}
}
The class PhoneBook contains both the data and the search method.
The search method returns a reference to the PhoneEntry
that matches the name being sought.