Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中循环通过数组_Java - Fatal编程技术网

在java中循环通过数组

在java中循环通过数组,java,Java,我正在开发一个程序,该程序在数组中搜索以匹配字符串。我目前已将其设置为,当没有匹配项时,将打印以下内容:未找到任何记录。我的问题是,它会在每次迭代中打印文本。我怎样才能更改它,使它只打印一次?这是我的密码: public static Employee[] searchWithId(Employee[] list, String search) { System.out.println("Searching for the id number: " + search); Empl

我正在开发一个程序,该程序在数组中搜索以匹配
字符串
。我目前已将其设置为,当没有匹配项时,将打印以下内容:
未找到任何记录
。我的问题是,它会在每次迭代中打印文本。我怎样才能更改它,使它只打印一次?这是我的密码:

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

提前谢谢

这应该可以解决你的问题,在寻找雇员时,如果我找到他,我就退出循环,什么也不做,但是如果我找不到他,我就退出循环,我会打印消息

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

简短而直接的回答是:

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

但是,对于Java 8,重写有几个优点:

  • 您可以根据条件过滤出元素
  • 您可以将元素收集到适当的集合中,例如
    List
    (如果确实需要,可以将其转换回数组)
  • 代码更简洁,表达能力更强;从下面的lambdas可以清楚地看出,您正在进行过滤
下面是为与Java8一起使用而重写的代码

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]);
}
公共静态员工[]搜索WithID(员工[]列表,字符串搜索){
System.out.println(“搜索id号:”+搜索);
最终列表过滤器deEmployees=Arrays.stream(列表)
.filter(e->e.getIdNumber().equals(搜索))
.collect(Collectors.toList());
if(filteredEmployees.isEmpty()){
System.out.println(“找不到id号的记录:“+搜索”);
}
返回filteredEmployees.toArray(新员工[0]);
}
我要说的是,让多个员工记录具有相同的ID是没有意义的,但这是我留给您的决定。

这不是在数组中编写java代码的好方法,而不是使用集合,而是用于此用例
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;
    }
公共静态员工[]搜索WithIDNew(员工[]列表,字符串搜索){ System.out.println(“搜索id号:”+搜索); 员工[]emps=新员工[list.length]; int指数=0; 布尔值=false;
对于(int j=0;jso…
break
循环?@KoosGadellaa我尝试使用break,但我的代码的第一位不起作用。添加一个布尔值来检查是否找到它,并根据它打印相应的消息,检查答案。它应该可以工作。使用布尔值来存储是否找到任何记录,如果没有找到记录,则打印它如何?我仍然这样做获取打印
在程序的第一部分中没有找到id号的记录。它在数组中迭代并打印,直到找到字符串。我如何才能摆脱它?@NikolasCharalambidis我在c中的意思是布尔值,它是布尔值。@Deescomaster你还多次收到此消息吗?@ShlomiHaver在我删除
该程序已启动,则在
中取消!
worked@Deescomaster如果您删除了“!”,它就不会工作。