213k views
2 votes
PLEASE HELP IN JAVA

A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes as input an integer N that represents the number of word pairs in the list to follow. Word pairs consist of a name and a phone number (both strings), separated by a comma. That list is followed by a name, and your program should output the phone number associated with that name. Output "None" if name is not found. Assume that the list will always contain less than 20 word pairs.

Ex: If the input is:

3 Joe,123-5432 Linda,983-4123 Frank,867-5309 Frank

the output is:
867-5309

Your program must define and call the following method. The return value of getPhoneNumber() is the phone number associated with the specific contact name.
public static String getPhoneNumber(String[] nameArr, String[] phoneNumberArr, String contactName, int arraySize)

Hint: Use two arrays: One for the string names, and the other for the string phone numbers.

1 Answer

6 votes

Answer: import java.util.Scanner;

public class ContactList {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

// Read the number of word pairs in the list

int n = scnr.nextInt();

scnr.nextLine(); // Consume the newline character

// Read the word pairs and store them in two arrays

String[] names = new String[n];

String[] phoneNumbers = new String[n];

for (int i = 0; i < n; i++) {

String[] parts = scnr.nextLine().split(",");

names[i] = parts[0];

phoneNumbers[i] = parts[1];

}

// Read the name to look up

String name = scnr.nextLine();

// Call the getPhoneNumber method to look up the phone number

String phoneNumber = getPhoneNumber(names, phoneNumbers, name, n);

// Print the phone number, or "None" if the name is not found

if (phoneNumber != null) {

System.out.println(phoneNumber);

} else {

System.out.println("None");

}

}

public static String getPhoneNumber(String[] nameArr, String[] phoneNumberArr, String contactName, int arraySize) {

// Search for the name in the array and return the corresponding phone number

for (int i = 0; i < arraySize; i++) {

if (nameArr[i].equals(contactName)) {

return phoneNumberArr[i];

}

}

// If the name is not found, return null

return null;

}

}

Explanation: The program inputs the number of word sets, stores them in two clusters (names and phoneNumbers), and looks up a title by calling the getPhoneNumber strategy to return the comparing phone number. Prints phone number or "None" in the event that title not found. getPhoneNumber strategy takes nameArr, phoneNumberArr, contactName, and arraySize as contentions. The strategy looks for a title and returns the phone number in case found, something else invalid.

User Noriaki
by
8.4k points

No related questions found