Improved 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. And I am sure that you have already done this.

Improved Program

Improved program:

. . .

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") );

    String name;
    Scanner scan = new Scanner( System.in );

    System.out.print("Enter name -->");
    name = scan.next();

    while( !name.equals("quit" ) )
    {
      int spot = phone.indexOf( new Entry( name, null ) ) ;

      if ( spot >= 0 )
        System.out.println( phone.elementAt( spot ) ) ;
      else
        System.out.println( name + " not found" ) ;

      System.out.print("Enter name -->") ;
      name = scan.next();
    }
 
  }
}

Of course, this is only a small example and not a practical program. But the techniques it uses are used in many industrial-strength programs.

QUESTION 27:

The program would be more practical if the user had more freedom in entering the target name. For example, the user should be able to enter all lower case or all upper case. Where would you make a change to the program to allow this?