Due: Wednesday, October 31
Goal: More Array Handling
Listed below is a class. Your task in this drill is to complete the lookupName
method.
The purpose of this method is to take a target name, an array of names, and an array of phone numbers.
The two arrays are set up so that the corresponding name and phone number are in the same index in their
respective arrays. The method should use a loop to search through the array of names, and if a name is
found that matches the target name, then return the corresponding string from the phone number array.
If the target name is not found in the array of names then "Unknown" should be returned as the phone
number.
The main method sets up the array of names and numbers for your phone book.
It then has a loop where the user can enter a name.
The lookupName
method is then called with the name typed in, the array of names, and the
array of numbers.
import java.util.Scanner;
public class PhoneBook
{
// *** TO DO: Complete this method so it searches through the array of names using
// *** a loop. If the name matches the target Name then return the corresponding
// *** phone number. If the name is not in the array then return "Unknown" as the
// *** phone number.
private static String lookupName(/* Fill in parameter list to match the call below */)
{
}
// **** You don't need to change anything in the main method ***** //
public static void main(String[] args)
{
// Arrays for four names and numbers
String[] names = new String[4];
String[] phoneNumbers = new String[4];
// Add five names and phone numbers
// where a name corresponds to the phone number
// at the same index in the array
names[0] = "Michael Myers";
phoneNumbers[0] = "333-8000";
names[1] = "Ash Williams";
phoneNumbers[1] = "333-2323";
names[2] = "Jack Torrance";
phoneNumbers[2] = "333-6150";
names[3] = "Freddy Krueger";
phoneNumbers[3] = "339-7970";
// Loop to enter a name and look up the phone number
String targetName;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter a name to look up the phone number, or enter to quit.");
targetName = keyboard.nextLine();
if (!targetName.equals(""))
{
// ***** The call to the method you have to finish is right here ***
String phone = lookupName(targetName, names, phoneNumbers);
System.out.println("The phone number for " + targetName + " is " + phone);
System.out.println();
}
} while (!targetName.equals(""));
}
}
As usual, show working code to your instructor by the end of the day or email to kenrick@uaa.alaska.edu