Playful Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Of course. Playing with things always helps to understand them.

Playful Program

Here is the program, just as before, but with some added statments that might help show what is going on.

import java.util.* ;

class Entry
{
  private String name;
  private String number;

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

  // methods
  public String getName()
  {
    return name ;
  }

  public String getNumber()
  {
    return number ;
  }

  public boolean equals( Object other )
  {
   
    System.out.print  ("    Compare " + other + " To " + this );
    System.out.println(" Result: " +  name.equals( ((Entry)other).name ) );
    return getName().equals( ((Entry)other).getName() );
  }

  public String toString()
  {
    return "Name: " + getName() + "; Number: " + getNumber() ;
  }
 
}

class PhoneBookTest
{
  public static void main ( String[] args)
  {
    ArrayList<Entry> phone = new ArrayList<Entry>();

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

    // Look for Hal in phone. The indexOf() method uses the
    // equals(Object) method of each object in the list.
    // 

    System.out.println("Begin Search" );
    int spot = phone.indexOf( new Entry( "Hal", null ) ) ;
    System.out.println("End Search" );

    System.out.println( "indexOf returns: " + spot ) ;
  }
}

Copy the program to a file and run it. Play with it for a while.

QUESTION 26:

Could the program be altered so that it searches for a name entered by the user?

(It would be good practice for you to do this before you go on.)