Yes, of course. You need to watch out for null
s, though.
Here is some code with search()
partially finished:
search()
returns
either a reference to the correct entry,
or null
if the entry could not be found.
class PhoneEntry
{
private String name; // name of a person
private String phone; // their phone number
. . . . .
}
class PhoneBook
{
private PhoneEntry[] phoneBook;
public PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 5 ] ;
. . . . . .
}
public PhoneEntry search( String targetName )
{
// use linear search to find the targetName
for ( int j=0; j < phoneBook.; j++ )
{
if ( phoneBook[ j ] != null && phoneBook[ j ].getName().equals( targetName ) )
return phoneBook[ j ];
}
return null;
}
}
Common Trick: Recall that &&
is a short-circuit operator.
This means that as soon as it find a false
, evaluation of the complete Boolean expression stops.
Look at this expression:
phoneBook[ j ] != null && phoneBook[ j ].getName().equals( targetName )
If the j'th
cell of phoneBook
is null, the right side of the expression is not evaluated
because the entire expression is false
, no matter what.
(Review: ) Say that phoneBook[ j ] != null
is true
.
What possible values might the entire expression have?