I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the if-else statement with the for-loops). Any advice would be greatly appreciated.
Additionally, this needs to be done with an array list as that is my assignment requirement. I have all my code working, and it is not due for a few days, so I am looking for ways to improve it while extending my learning beyond the classroom.
The numberOfContacts
variable is fed into the method from the main method, which gets the count from another method that reads through a text file to get the number of contacts.
/**
* search method searches through the contact list for a given criteria
* and displays all results.
* @param searchString is type String.
* @param type is type String.
* @param numberOfContacts is type int.
* @param contacts is type Person[].
*/
public static void search(String searchString, String type, int numberOfContacts, Person[] contacts) {
// Initialize variables for results
int found = 0;
int[] results = new int[numberOfContacts];
// Determine the type of search
if (type.equals("name")) {
// Search by name
for (int x = 0; x < numberOfContacts; x++) {
if (contacts[x].getName().contains(searchString)) {
results[found] = x;
found++;
}
}
} else {
// Search by phone
for (int x = 0; x < numberOfContacts; x++) {
if (contacts[x].getPhone().contains(searchString)) {
results[found] = x;
found++;
}
}
}
// Display the search results
System.out.println("\n\t**************");
System.out.println("\tSearch Results");
System.out.println("\t**************");
System.out.println("Found " + found + " results containing \"" + searchString + "\":");
System.out.println();
if (found > 0) {
for (int x = 0; x < found; x++) {
System.out.println(contacts[results[x]].getName() + "\t" + contacts[results[x]].getPhone());
}
}
System.out.println("\n\n\n");
}