I'm starting out on Java and I'm creating a basic phonebook application.
I'd like to implement a "Search Contacts" function that searches through an ArrayList of contacts and returns a count of how many contacts match the user-inputted String using a for each loop and if statement.
Question is, is it possible to receive a count of the contacts that match the user's search input without first defining an int - say, int counter = 0;
- and then updating it within the if statement?
Below is an example of the only method I know could work to tally the number of matching contacts:
int counter = 0;
System.out.println("Please enter name of contact: ");
String nameRequest = scanner.nextLine();
for (Contact c: contactList) {
if (nameRequest.equals(c.getName())){
counter++;
System.out.println(counter + " contact(s) found"
System.out.println("Name: " + c.getName());
}
}
Extras: How could I go about so the code also returns contacts that are only a partial match? e.g. User inputs "Michael" but there are no contacts that only contain "Michael". There are however contacts called "Michael B Jordan" and "Michael Schumacher" which I'd like returned for the partial match.
Thanks in advance!