my program will ask the user his last name and his first name. after that it will do a search to see if the last name and firstname matches with the list. if it does then it prints out the phone number if not then it will say name not found which i have achieved it so far. so i was playing with the program a little bit. what i wanted to do is that when a user enters just the last name and hit enter for the first name then my program should print all the name and numbers which matches the last name. here is my code:
[B]import[/B] java.util.Scanner;
[B]class[/B] PhoneEntry
{
String firstName;
String lastName; // name of a person
String phone; // their phone number
PhoneEntry( String f, String l, String p )
{
firstName = f; lastName = l; phone = p;
}
}
[B]class[/B] PhoneBook
{
PhoneEntry[] phoneBook;
PhoneBook() // constructor
{
phoneBook = [B]new[/B] PhoneEntry[ 7 ] ;
phoneBook[0] = [B]new[/B] PhoneEntry(
"James ", "Barclay ", "(418)665-1223");
phoneBook[1] = [B]new[/B] PhoneEntry(
"Grace" , "Dunbar", "(860)399-3044");
phoneBook[2] = [B]new[/B] PhoneEntry(
"Paul", "Kratides", "(815)439-9271");
phoneBook[3] = [B]new[/B] PhoneEntry(
"Violet" , "Smith", "(312)223-1937");
phoneBook[4] = [B]new[/B] PhoneEntry(
"John", "Smith", "(913)883-2874");
phoneBook[5] = [B]new[/B] PhoneEntry(
"Suleman", "Smith", "(913)883-2874");
phoneBook[6] = [B]new[/B] PhoneEntry(
"Violet", "Dunbar", "(913)883-2874");
}
PhoneEntry search( String targetName )
{
[B]for[/B] ([B]int[/B] j=0; j<phoneBook.length; j++)
{
[B]if[/B] ( phoneBook[ j ].
lastName.equals( targetName))
[B]return[/B] phoneBook[ j ];
}
[B]return[/B] [B]null[/B];
}
}
[B]class[/B] PhoneBookTester
{
[B]public[/B] [B]static[/B] [B]void[/B] main (String[] args)
{
String firstName="";
String lastName="";
PhoneBook pb = [B]new[/B] PhoneBook();
Scanner scan = [B]new[/B] Scanner(System.in);
[B]do[/B] {
System.out.println("Enter the last name " );
lastName = scan.nextLine();
[B]if[/B](lastName.equals("quit")) [B]break[/B];
System.out.println("Enter the first name ");
firstName = scan.nextLine();
// search for "Violet Smith"
PhoneEntry entry =
pb.search( lastName );
[B]if[/B] ( entry != [B]null[/B] )
System.out.println( "The number is " + entry.phone );
[B]else[/B]
System.out.println("Name not found");
}[B]while[/B]([B]true[/B]);
System.out.println("Good Bye ");
}
}
this is what i have achieved rite now:
Last Name? SmithFirst Name? VioletThe number is: (312) 223-1937
this is what i have not achieved:
Last Name? SmithFirst Name?Violet Smith: (312)223-1937John Smith: (812) 339-4916Suleman Smith: (913)883-2874