2014-12-25 49 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

这应该工作(我也提高了一点 - 使用int,而不是双,用break一旦发现匹配):

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

谢谢你,我理解我的错误:) – Najme

相关问题