簡體   English   中英

循環遍歷java中的數組

[英]looping through an array in java

我正在開發一個搜索數組以匹配String 我目前設置了它,以便在沒有匹配項時打印以下內容: No record has been found 我的問題是它會在每次迭代中打印該文本。 我怎樣才能改變它,讓它只打印一次? 繼承人我的代碼:

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);
}

期望的輸出:

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

電流輸出:

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

提前致謝!

簡短而直接的答案:

因為您的打印語句包含在您的循環中,所以無論您的循環迭代多少次,它都會打印出來。 創建一個布爾值以方便是否找到該值(然后break循環)就足以打印出消息; 這個答案中已經指出了這個概念。

但是,使用 Java 8,您可以通過重寫獲得幾個優點:

  • 您可以根據條件filter元素。
  • 您可以將元素收集到適當的集合中,例如List<Employee> (如果您真的想要,可以將其轉換回數組)。
  • 代碼更簡潔,更具表現力; 從下面的 lambda 表達式中可以清楚地看出您正在過濾。

這是為與 Java 8 一起使用而重寫的代碼。

public static Employee[] searchWithId(Employee[] list, String search) {
    System.out.println("Searching for the id number: " + search);

    final List<Employee> filteredEmployees = Arrays.stream(list)
                                                   .filter(e -> e.getIdNumber().equals(search))
                                                   .collect(Collectors.toList());

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

    return filteredEmployees.toArray(new Employee[0]);
}

我會說,讓多個員工記錄具有相同的 ID 是沒有意義的,但這是我留給您自行決定的事情。

這應該可以解決您的問題,在尋找工作時,如果我找到他,我將退出循環並且什么也不做,但是如果我找不到他並且我退出了循環,我將打印該消息。

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);
}

添加了一個 bool 來檢查是否找到/未找到。

public static Employee[] searchWithId(Employee[] list, String search){
    System.out.println("Searching for the id number: " + search);
    Employee[] filteredEmployees = new Employee[list.length];
    boolean recordExist = false;
    int index = 0;
    for (Employee list1 : list) {
        if (list1.getIdNumber().equals(search)) {
            System.out.println("Found id number: " + search);
            recordExist = true;
            filteredEmployees[index++] = list1;
            String filtered = Arrays.toString(filteredEmployees).replace("[","").replace("]","").replace("null", "").replace(",", "");
            System.out.println(filtered);
        }
    }
     if (!recordExist)
       System.out.println("No record has been found for the id number: " + search);
     return Arrays.copyOfRange(filteredEmployees, 0,index);
}
This is not a good way to write java code in arrays instead use Collections but for this use case

public static Employee[] searchWithIdNew(Employee[] list, String search){
        System.out.println("Searching for the id number: " + search);
        Employee[] emps = new Employee[list.length];
        int index=0;
        boolean found = false;
        for(int j=0;j<list.length;j++) {
            Employee emp = list[j];
            if(emp.getIdNumber().equals(search)) {
                System.out.println("Found id : "+ search+" at index :"+j);
                emps[index++] = emp;
                found=true;
            }
        }
        if(!found) {
            System.out.println("No record has been found for the id number: " + search);
        }
        return emps;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM