2011-03-22 2 views
1

사람 목록의 peoplelist라는 배열 목록을 검색하는 각 루프에 대해 작성하는 데 도움이 필요합니다. 루프는 배열의 문자열 우편 번호 및 문자열 이름을 검색해야합니다. 그런 다음 ID가 있으면 ID를 리턴해야하며, ID가 없으면 리턴해야합니다. 어떤 종류의 도움도 좋을 것입니다!각 루프마다 a를 사용하여 배열 목록에서 두 요소를 찾습니다.

+1

이 숙제가 있습니까? – SWeko

+1

배열 목록에서 "두 요소"를 찾는 것이 아니라 배열 목록에있는 모든 "People"요소의 "두 속성"을 찾는 것처럼 보입니다. 옳은? '피플 (People) '수업이 어떻게 생겼는지 알려 주실 수 있나요? – MarcoS

+0

네, 죄송합니다. 2 초를 넘겨 줄 코드를 얻을 수도 있습니다 – Jimmy

답변

0
//In case multiple persons match :) 
List<String> result = new LinkedList<String>(); 

for (People person : peopleList) { 
    if (person.getName().equals(name) && person.getPostcode().equals(postCode)) 
    result.add(person.getId()); 
} 

if(result.isEmpty()){ 
    return null; 
}else{ 
    return result; 
} 
+0

대단히 고마워! – Jimmy

2

은 수업에 대해 많은 가정을해야하지만,이 같은 충분해야한다 : "두 가지 요소"와

for (People person : peoplelist) { 
    if (person.getPostCode().equals(postcode) && person.getName().equals(name)) { 
     return person.getId(); 
    } 
} 
// deal with not being found here - throw exception perhaps? 
1

, 당신은 "일부 클래스의 두 속성"을 의미합니까? 그렇다면,이 라인을 따라 뭔가를 할 것이다 :

for (People person : peopleList) { 
    if (person.getName().equals(name) && person.getPostcode().equals(postCode)) 
    return person.getId(); 
} 
return null; 

: 클래스 People (즉, 표준 getter 메소드와) Java Bean의 같은 기록

String id = null; 
for(People p : peoplelist) { 
    if(somePostcode.equals(p.postcode) && someName.equals(p.name)) { 
     id = p.id; 
     break; // no need to continue iterating, since result has been found 
    } 
} 
// result “id” is still null if the person was not found 
3

경우,이 같은 일을 할 것입니다 사람의 이름이나 우편 번호가 null 일 수있는 경우 equals 전화를 뒤집어 null 포인터 예외가 발생하지 않도록 할 수 있습니다 (예 : person.getName().equals(name) 대신 name.equals(person.getName())).

Btw Person이 더 좋습니다.

0
People foundPerson; 
for (People eachPeople : peoplelist) 
{ 
    if (Integer.valueOf(eachPeople.getID()) == 10054 
     && "Jimmy".equals(eachPeople.getName())) 
    { 
     foundPerson= eachPeople; 
     break; 
    } 
} 
0

당신은 당신이 누구의 postcodename 경기 일부 값 Person의 모든 인스턴스를 검색하려면 다음 경우 Person 콩을 가정 할 때, 당신은 같은 것을 할 수 있습니다

public List<Person> searchFirst(List<Person> persons, String postcode, String name) { 
    List<Person> matchingPersons = new ArrayList<Person>(); 
    for (Person person : persons) { 
     if (person.getPostcode().equals(postcode) && person.getName().equals(name)) 
      matchingPersons.add(person); 
    } 
    return matchingPersons; 
} 

다음 시간, 코드를 보여줄 수 있으므로 잘못을 이해하는 데 도움이됩니다.

+0

오케이 죄송합니다.이 사이트를 처음 접해 보았습니다. 시도해 보았습니다.하지만 for-each 루프를 사용하는 것은 처음이고 이해하기 쉽도록 간단한 예제를 찾을 수 없습니다. :) – Jimmy

관련 문제