Я уже некоторое время смотрю на этот код, и я думаю, что есть способ его оптимизировать (а именно оператор if-else с помощью for-loops). Любые советы будут очень признательны.Оптимизация If-statement with for-loop
Заранее благодарен!
/**
* 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");
}
Вы пытаетесь оптимизировать скорость или читаемость? – Tharwen
используйте шаблон стратегии, чтобы быть более элегантным, используя такие интерфейсы, как 'Searchable' с методом поиска. – nachokk
Я ищу, чтобы оптимизировать его для скорости. Я хотел бы удалить избыточную логику и т. Д. Я совершенно не привык к программированию, и я просто возвращаюсь в школу для получения степени компьютерной науки. Попытка расширить мое обучение за пределами класса. – user2778322