Deescomaster Deescomaster - 4 months ago 13
Java Question

looping through an array in java

I'm working on a program that searches through an array to match a

String
. I currently have it set so that when a there is no match the following is printed:
No record has been found
. My problem is that it prints that text in every iteration. How can i change it so it prints it only once? heres my code:

public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee[] filteredEmployees = new Employee[list.length];
int index = 0;
for (Employee list1 : list) {
if (list1.getIdNumber().equals(search)) {
System.out.println("Found id number: " + search);
filteredEmployees[index++] = list1;
String filtered = Arrays.toString(filteredEmployees).replace("[","")
.replace("]","").replace("null", "").replace(",", "");
System.out.println(filtered);
} else if (!(list[index].getIdNumber().equals(search))) {
System.out.println("No record has been found for the id number: " + search);
}
}
return Arrays.copyOfRange(filteredEmployees, 0,index);
}


Desired output:

Searching for the id number: P102432
No record has been found for the id number: P102432


Current output:

Searching for the id number: P102432
No record has been found for the id number: P102432
No record has been found for the id number: P102432
No record has been found for the id number: P102432
No record has been found for the id number: P102432
No record has been found for the id number: P102432
No record has been found for the id number: P102432


thanks in advance!

Answer

This should solve your problem, while looking for the employ if i found thim i exit the loop and do nothing, but if i can't find him and i got out of the loop i will print the message.

public static Employee[] searchWithId(Employee[] list, String search){
    System.out.println("Searching for the id number: " + search);
    Employee[] filteredEmployees = new Employee[list.length];
    boolean resultFound = false;
    int index = 0;
    for (Employee list1 : list) {
        if (list1.getIdNumber().equals(search)) {
            System.out.println("Found id number: " + search);
            filteredEmployees[index++] = list1;
            String filtered = Arrays.toString(filteredEmployees).replace("[","").replace("]","").replace("null", "").replace(",", "");
            System.out.println(filtered);
            resultFound = true;
            break;
        }
    }

    if(!resultFound){
          System.out.println("No record has been found for the id number: " + search);
    }

     return Arrays.copyOfRange(filteredEmployees, 0,index);
}
Comments