Home > Net >  How to Println statement only once when searching in for loop through ArrayList?
How to Println statement only once when searching in for loop through ArrayList?

Time:10-20

I am trying to figure out a way to make my Program print the Println statements once, so if a friend is found it says: Following Friends have been found: -f1 -f2 -f3 or the No Friend found statement only once.

Right now it prints the Println every time it iterates through the loop...

Any help please?

public void searchName(String lastName) {
        
        for(Friend friend: listofFriends) {
            if ( lastName!= friend.getlastName() ) {
                System.out.println("No Friend found");
                }
                                
            else    {       System.out.println("Following Friends have been found: ");

                System.out.println(friend.getFirstName() " " friend.getLastName());}    

            }}

CodePudding user response:

Thank you @cyberbrain. If anybody is interested, here is how i got my code to work.

public void searchName(String lastName) {
    StringBuilder builder = new StringBuilder();
    for(Friend friend: listofFriends) {
        if ( friend.getlastName().equalsIgnoreCase(lastName)) { 
            builder.append(friend.getFirstName() " " friend.getlastName() "\n");}}
        if(builder.isEmpty()) {
            System.out.println("No Friend found");}
        
        else {System.out.println("Following Friends have been found:");
            System.out.println(builder);}}

CodePudding user response:

You have several issues in your code:

  1. you do not use String.equals to compare your strings, but ==. This may only work as long as you are using string literals in Java, as the compiler uses the same reference for equal literals. As soon as you use a user input or similar, it will fail.

  2. for each friend whose lastname does not match, you will print "No Friend found" - probably once for every entry in the list, if no friend matches.

  3. what you don't like: the friends are not listed, but an individual sentence is printed per match.

To tackle the first is simple, you probably already found out. The good news is that you can solve #2 and #3 in one go:

Create a StringBuilder before the loop. In the loop for every friends name that matches, you add the firstname, lastname and a separator with .append to the StringBuilder. You don't do anything if an entry does not match.

After the loop, you check if the StringBuilder is empty - if yes, you can output "No Friend found", if it has content, you remove the last delimiter again, and print the result.

  • Related