Find a value in an array?

advertisements

I am trying to search for the value in an array. The results keep coming back as nothing though. I am assuming my loop isnt proper, could you assist me in what i am doing wrong?? It is suppose to use the value held in "searchFor" and match up. Then display the value in Printer.printPersonList.

    public static ArrayList<Person> findPerson(String searchFor) {
    ArrayList<Person> matches = new ArrayList<>();
    for (Person p : personList) {
        boolean isAMatch = false;

        if (p.getFirstName().equalsIgnoreCase(searchFor)) {
            isAMatch = true;

        } else if (p.getLastName().equalsIgnoreCase(searchFor)) {
            isAMatch = true;

        } else if (p.getSocialSecurityNumber().contains(searchFor)) {
            isAMatch = true;
            ;
        } else if (String.format("%d", p.getAge()).equals(searchFor))
            if (isAMatch) {

                matches.add(p);
            }

        Printer.printPersonList(matches);

    }
    return matches;

}


This is from printer.java

public static void printPersonList(ArrayList<Person> personListToPrint) {

    System.out
            .printf("\nLast Name           First Name           Social Security Number  Age\n");
    System.out
            .printf("=================== ===================  ======================  ===\n");
    for (Person p : personListToPrint) {

        System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
                p.getLastName(), p.getSocialSecurityNumber(), p.getAge());

    }


The problem with your algorithm is that you are setting isAMatch as true if the Person's first name is equal to the key that you are searching for, but not adding the person to the list. Here's the segment that's flawed:

...code omitted...

} else if (String.format("%d", p.getAge()).equals(searchFor))
            if (isAMatch) {

                matches.add(p);
            }

        Printer.printPersonList(matches);

    }

...code omitted...

The if(isAMatch) code is only executed if String.format("%d", p.getAge()).equals(searchFor) - there are no open/close parentheses afterwards to indicate a code block.