循环遍历java

时间:2016-07-09 09:06:42

标签: 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

提前感谢!

4 个答案:

答案 0 :(得分:3)

简短而直接的回答:

因为你的print语句包含在你的循环中,所以无论你的循环迭代多少次都会打印出来。创建一个布尔值以方便是否找到该值(然后break退出循环)就足以打印出该消息; this answer已经指出了这个概念。

但是,使用Java 8,重写时可以获得几个优点:

  • 您可以根据条件filter元素。
  • 您可以将元素收集到适当的集合中,例如List<Employee>(如果您真的想要,可以将其转换为数组)。
  • 代码更清晰,更具表现力;从下面的lambdas可以清楚地看到你正在过滤。

这是为了与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是没有意义的,但这是我自行决定的。

答案 1 :(得分:2)

这应该可以解决你的问题,同时寻找工作,如果我发现我退出循环并且什么都不做,但是如果我找不到他并且我离开了循环,我将打印消息。 / p>

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

答案 2 :(得分:-1)

添加了一个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);
}

答案 3 :(得分:-1)

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