2016-07-09 2 views
-3

배열을 통해 String과 일치하는 프로그램을 검색하고 있습니다. 나는 현재 일치하지 않을 때 다음이 인쇄되도록 설정했습니다 : No record has been found. 내 문제는 모든 반복에서 텍스트를 인쇄한다는 것입니다. 어떻게 한 번만 인쇄하도록 변경할 수 있습니까? 를 heres 내 코드 :배열을 통해 자바 루핑

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 

감사합니다!

+0

그래서 ... 'break' the loop? –

+0

@KoosGadellaa 나는 break를 사용하려고했지만, 그때 나의 코드의 첫번째 비트는 작동하지 않았다. – Deescomaster

+0

부울 값을 추가하여 발견되었는지 여부를 확인하고 그에 따라 적절한 메시지를 인쇄하십시오. 응답을 확인하십시오. 작동해야합니다. –

답변

2

이것은 내가 루프를 빠져 나가서 아무 것도하지 않는 것을 발견하면 채용을 찾는 동안 문제를 해결해야합니다. 그러나 내가 그를 찾을 수 없으면 루프에서 빠져 나와 메시지를 인쇄 할 것입니다.

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

나는 여전히 프로그램의 첫 번째 부분에 'ID 번호에 대한 레코드가 없습니다'라는 인쇄본을 얻습니다. 그것은 배열을 반복하고 문자열이 발견 될 때까지 출력합니다. 어떻게 그걸 없앨 수 있니? – Deescomaster

+1

'bool '이란 무엇입니까? –

+0

@ NikolasCharalambidis 부울은 C#에서 부울을 의미합니다. –

-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

짧고 직접 답 : 인쇄 문 루프에 포함되어 있기 때문에

, 그것은 그러나 여러 번 루프 반복을 인쇄합니다. 값을 찾았는지 아닌지를 확인하기 위해 부 울린을 생성하면 (그리고 나서 break이 루프 밖으로 빠져 나옵니다) 메시지를 출력하면 충분합니다. 이것의 개념은 this answer에 지적되었습니다.

  • 당신이 조건에 filter 요소 아웃을 기반으로 할 수 있습니다

    그러나, 자바 8, 당신이 재 작성으로 얻을 수있는 몇 가지 장점이있다.

  • List<Employee>과 같은 적절한 컬렉션으로 요소를 수집 할 수 있습니다 (원하는 경우 배열로 되돌릴 수 있음).
  • 코드는 훨씬 깨끗하고 표현력이 풍부합니다. 아래 람다에서 당신이 걸러 내고 있다는 것이 확실합니다. 여기

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