2017-03-24 1 views
0

나는 hashMaps에 관해 뭔가를 보았지만, 우리는 그 일을 멀리하지 않았다. 답변과 도움이되는 제안은 관리 할 수있는만큼 간단하게하십시오.목록에서 사용자 지정 데이터 형식의 값을 계산하는 방법은 무엇입니까?

나는 이미 만들어진 Color라는 완벽하게 작동하는 사용자 지정 데이터 형식이 있습니다. 유형의 유일한 값은 Color.BLUE, Color.RED, Color.YELLOW 및 Color.GREEN입니다.

내 작업은 다른 색상보다 목록에 더 많은 Color.BLUE가있는 경우 Color.BLUE를 반환하고 다른 색상보다 목록에 더 많은 Color.RED가 있으면 Color.RED를 반환하려면 Color와 동일합니다. 녹색과 컬러. 노란색. 내가 연구하고하고있다

이 코드를 내놓았다 :

public Color callColor(List<Card> hand) { 

    int blueCards = Collections.frequency(hand, Color.BLUE); 
    int redCards = Collections.frequency(hand, Color.RED); 
    int greenCards = Collections.frequency(hand, Color.GREEN); 
    int yellowCards = Collections.frequency(hand, Color.YELLOW); 
    Color changeColorTo = Color.NONE; 

    if ((blueCards > redCards) || (blueCards > greenCards) || (blueCards > yellowCards)) { 
     changeColorTo = Color.BLUE; 
    } 

    if ((redCards > blueCards) || (redCards > greenCards) || (redCards > yellowCards)) { 
     changeColorTo = Color.RED; 
    } 

    if ((greenCards > redCards) || (greenCards > blueCards) || (greenCards > yellowCards)) { 
     changeColorTo = Color.GREEN; 
    } 

    if ((yellowCards > redCards) || (yellowCards > greenCards) || (yellowCards > blueCards)) { 
     changeColorTo = Color.YELLOW; 
    } 
    return changeColorTo; 
} 

하지만 그들은 확실히 제로이어야한다 때이 코드는 0으로 blueCards, redCards, greenCards 및 yellowCards 모든됩니다.

그래서이 경우 내 Collections 구현이 전혀 작동하지 않았습니다. 도움!

+1

에 대한 카드 수를 알아내는 반복적 인 방법은

다음은? – Sanjeev

+0

@Sanjeev 확실하지 않습니다. 코드의 해당 부분이 우리에게 제공되었습니다. – hattic

+1

'Color' 클래스의 코드를 게시 할 수 있습니까? – Sanjeev

답변

2

List<Card>을 메서드에 전달했지만 해당 목록의 특정 Color 빈도를 검색하고 있습니다. 그래서 모든 수는 0과 같습니다.

+0

우리는'public Color callColor (List 손) {'와 함께 제공되었고 아래에 코드를 쓰라고했습니다. 어떻게 수정해야합니까? – hattic

+0

Java 8을 사용하는 경우에는'int blueCards = hand.stream(). filter (h -> Color.BLUE.equals (h.getColor())). count();'와 같이 사용하십시오. – Farrandu

+0

감사!! 나는 그것을 바르게 평가한다 – hattic

1

입력 목록에 카드 색상이 없습니다.

hand.stream().map(Card::getColor).collect(Collectors.toList()); 

당신이 지금에 Collection.frequency을 사용할 수 있도록, 색상의 목록을하지 얻을 것이다 결과 :

그래서 가능한 문제 해결이 먼저 색상 목록에 당신에게 카드 목록을 변환하는 것입니다 초기 카드 목록에.

그러나 다른 컬렉션 사용과 같이 문제를 해결할 수있는 많은 방법이 있습니다.

0

Collections#frequency은 지정된 컬렉션에서 전달 된 객체의 발생을 조회하지만 귀하의 경우에는 카드 모음의 속성과 일치하기를 원합니다. 그래서 모든 주파수 계산에 대해 0을 제공합니다. 어떻게 '목록을 hand`하고 있습니다 각 색상

for(Card card:hand) { 

    if(card color is equal to Color.Blue) blueCards++ 
    else if(card color is equal to Color.Red) redCards ++ 

    // same code for other colors 
} 
+0

이것은 매우 많이 도움이된다! !!! – hattic

+0

도움이 된 것을 기쁘게 생각합니다 :) – Sanjeev

관련 문제