2014-12-25 5 views
0

문자열 배열이 있으므로 정렬되지 않으며 중복 요소가 있습니다. 별개의 요소를 계산하고 싶지만, 내 메서드를 호출하면 별개의 요소가 아니라 모든 요소의 수를 반환합니다. 제발, 제발요.정렬되지 않은 문자열 배열의 고유 요소 찾기

public static double countDistinctString(String[] array) { 
     double distinctStrings = 0; 
     for (int j = 0; j < array.length; j++){ 
      String thisString = array[j]; 
      boolean seenThisStringBefore = false; 
      for (int i = 0; i < j; i++){ 
       if (thisString == array[i]){ 
        seenThisStringBefore = true; 
       } 
      } 
      if (!seenThisStringBefore){ 
       distinctStrings++; 
      } 
     } 
     return distinctStrings; 
    } 
} 

답변

0

문제는 ==을 사용하여 문자열을 비교하는 것입니다. 이 기능이 작동하지 않는 이유는 How do I compare strings in Java?을 참조하십시오. 대신 if (thisString.equals(array[i]))을 사용하십시오.

+0

덕분에 너무 많은, 문제가 해결

public static double countDistinctString(String[] array) { int distinctStrings = 0; for (int j = 0; j < array.length; j++) { String currentString = array[j]; boolean seenThisStringBefore = false; for (int i = 0; i < j; i++){ if (currentString.equals(array[i])) { seenThisStringBefore = true; break; } } if (!seenThisStringBefore) { distinctStrings++; } } return distinctStrings; } 
: – Najme

0

이 작동합니다 (I는 또한 조금 개선했습니다 - 휴식을 사용하는 대신에 이중의 사용 INT를 한 번에 볼 수있는 경기) :

+0

당신, 내가 감사 이해 내 실수 :) – Najme