Searching a Array for unique name using method

Aidan Ward :

so i had a exam to day and while i found a way to make my code work i dont like it

    public static void search(String name, Friend[] array) {

    for (int i = 0; i<array.length;i++) {

        if((array[i].getName()).equals(name)) {
            System.out.println(name+ " is found at position " +i+"\n");
        }
        else {
            System.out.print("\nName not in list\n");
        }
    }
}

So what i do here works, im searching the array of type Friend for a name ive passed from the main method. But i want to stop when it finds a unique name, so while i like what i have as it shows if there is more than one of the name i would like to show just the ones say that contain John and ignore every other name or if there is no John that it would just print a single "Name not in list"

Villat :

You can add a break and also have a boolean to avoid printing the same message over and over:

boolean nameFound = false;
for (int i = 0; i<array.length;i++) {
    if((array[i].getName()).equals(name)) {
        System.out.println(name+ " is found at position " +i+"\n");
        nameFound = true;
        break;
    }
}

if(!nameFound) System.out.print("\nName not in list\n");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328568&siteId=1