ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
30. Improved Program
Answer:
Of course. And I am sure that you have already done this.
Improved Program
. . . public 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.println(); System.out.print("Enter name -->") ; name = scan.next(); } } } |
COf course, this is only a small example and not a practical program. But it uses techniques found in many industrial-strength programs.
Question 29:
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?