Java Write a program that has two parallel arrays of String objects. One of the
ID: 3599458 • Letter: J
Question
Java
Write a program that has two parallel arrays of String objects. One of the arrays should hold people's names and the other should hold their phone numbers. Here are your sample contents of both arrays:
name Array Contents phone Array Contents
"Harrison, Rose" "555-2234"
"James, Jean" "555-9098"
"Smith, William" "555-1785"
"Smith, Brad" "555-9224"
The program needs to ask the user to enter a name or the first few characters of a name in search for the array. It should then display all of the names that match the user's input and their corresponding phone #'s. For example, if the user entered "Smith", the program should display the following names and phone #'s from the list:
Smith, William: 555-1785
Smith, Brad: 555-9224
*The problem I have is I need to create two classes. One is for "PhoneList", which should hold all the methods, and the second "PhoneListTest" which gets the methods from the "PhoneList" class and incorporate it into the demo/test file.
Explanation / Answer
PhoneListTest.java
import java.util.Scanner;
public class PhoneListTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name or the first few characters of a name in search: ");
String name = scan.nextLine();
PhoneList p = new PhoneList();
String result = p.findNames(name);
if(result.equals("")) {
System.out.println("No names found");
} else {
System.out.println(result);
}
}
}
PhoneList.java
public class PhoneList {
private String nameArray[] = {"Harrison, Rose", "James, Jean","Smith, William" , "Smith, Brad" };
private String phoneArray[] = {"555-2234", "555-9098", "555-1785" , "555-9224"};
public String findNames(String name) {
String s = "";
for(int i=0;i<nameArray.length;i++) {
if(nameArray[i].contains(name)) {
s = s + nameArray[i]+": "+phoneArray[i]+" ";
}
}
return s;
}
}
Output:
Enter the name or the first few characters of a name in search:
Smith
Smith, William: 555-1785
Smith, Brad: 555-9224
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.