2017-10-07 3 views
-1

이 메서드는 가장 인기있는 친구를 반환합니다. 나는이 루프가 arraylist에 getFriend().size() > 0을 가진 객체를 추가 할 것이라고 생각한다. 그런 다음 다음 객체 getFriend().size()과 ArrayList에있는 객체를 비교합니다. Object가 더 많이 ArrayList에 추가되고 다른 객체는 더 많은 친구가 있으면 제거됩니다.내 foreach 루프가 작동하지 않습니다.

// Class variables 

// the person's name 
private String name; 
// a list of this person's friends 
private ArrayList<Person> friends; 

public Person mostConnectedFriend(){ 
    for(Person f : friends){ 
     ArrayList<Integer> mostFriends = new ArrayList<>(); 
     int amountOfFriends = 0; 
     if(getFriends().size() > amountOfFriends){ 
      mostFriends.remove(amountOfFriends); 
      mostFriends.add(amountOfFriends); 
     } 
    } return null; 
}  
+4

성취하려는 것은 무엇입니까? –

+0

[ "does not work]"(http://importblogkit.com/2015/07/does-not-work/)이라고 생각하는 이유를 설명해 주시겠습니까? 이 코드에서 무엇을 기대했으며 대신 무엇을 얻었습니까? – Pshemo

+0

대부분 "연결된"친구입니까? –

답변

3

당신이 보여 코드가 Person 클래스 내에 있다고 가정하면, 당신은 자신의 친구의 가장 큰 번호가 this 사람의 친구 중 어떤 알아 내려고하고 있는지, 다음이 작동 할 수 있습니다 :

public Person mostConnectedFriend() { 
    int highestFriendCount = 0; 
    Person friendWithHighestFriendCount = null; 
    for (Person friend : friends) { 
     int friendCount = friend.friends.size(); 
     if (friendCount > highestFriendcount) { 
      highestFriendCount = friendCount; 
      friendWithHighestFriendCount = friend; 
     } 
    } 
    return friendWithHighestFriendCount; 
} 

이것은 친구 인 this 인물을 거쳐 지금까지 확인 된 다른 친구보다 더 많은 친구 수를 가진 친구를 찾을 때마다 카운트를 대체하고이 현재 친구를 추적합니다. 루프가 끝날 때까지 friendWithHighestFriendCount은 가장 연결된 친구를 보유하고 highestFriendCount은 보유한 친구의 수를 보유하게됩니다.

관련 문제