A good answer might be:

  • array[ j ] = target
    • NO! a horrible bug! This puts the reference in target into slot j of the array
  • array[ j ] == target
    • NO! a less horrible bug! This tests if the two references are the same (i.e, if they refer to the same one object.)
  • array[ j ].equals( target )
    • Yes! This checks if the two strings contain the same characters.

Return when Found

class Searcher
{
  // seek target in the array of strings.
  // return the index where found, or -1 if not found.
  public static int search( String[] array, String target )
  {
     for ( int j=0; j  < array.length; j++ )
       if ( array[j] != null )
         if ( array[j].equals( target ) ) return ________ ;

     return ________ ; // Outside of the Loop!
  }
}

class SearchTester
{
  public static void main ( String[] args )
  {
    . . . . . .
    int where = Searcher.search( strArray, "Peoria" );
    . . . . . .
  }
}

Unless you enjoy late nights debugging programs that will never run, look over those three answers. Two of them (the wrong ones) are very common bugs. They will happen to you. Learn to recognize them.

The program (left) has more of the search method. Inspect the second if statement. It is written so that if the target has just been found the method immediately returns to the caller with the index of the slot in which target was found.

The second return-statement is NOT part of the loop body. It is executed only when every slot of the array has been inspected and the target has not been found.


QUESTION 15:

You know what to do with those blanks.

Click Here after you have answered the question