2016-07-12 106 views
0
import java.util.StringTokenizer; 

class Count { 
    int count; 
    String name; 

    void SetCount(int c, String n) { 
     this.count = c; 
     this.name = n; 
    } 

    void Show() { 
     System.out.print("Word= " + name); 
     System.out.print(" Count= " + count); 
     System.out.println(); 
    } 
} 

class Contains2 extends Count { 
    public static void main(String args[]) { 
     String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out"; 
     int i, c2, j; 

     StringTokenizer st = new StringTokenizer(s, " "); 
     c2 = st.countTokens(); 

     String[] test = new String[c2]; 
     Count[] c = new Count[c2]; 

     for (i = 0; i < c2; i++) { 
      c[i] = new Count(); 
     } 

     i = 0; 

     while (st.hasMoreTokens()) { 
      String token = st.nextToken(); 

      test[i] = token; 
      c[i].SetCount(0, test[i]); 
      i++; 
     } 

     for (i = 0; i < c2; i++) { 
      for (j = 0; j < c2; j++) { 
       if (c[i].name.equals(test[j])) 
        c[i].count += 1; 
      } 
     } 

     for (i = 0; i < c2; i++) { 
      c[i].Show(); 
     } 
    } 
} 

所以我讓這個小程序來計算每個單詞在段落中重複的數量。它的工作按計劃,但現在我得到每一個字的重複,因爲我爲每個單獨的對象和打印他們全部。所以有什麼辦法可以刪除重複的單詞,我的意思是根據他們的名字刪除這些對象。我可以將它們設置爲null,但它仍然會打印它們,所以我只是想擺脫它們或以某種方式跳過它們從java中的對象數組中刪除對象

+1

我會用[HashMap的(https://docs.oracle.com/javase/8/docs/api/java/util/HashMap的.html)。 – Fildor

+0

HashMap非常適合您的場景,但是您可以將它們設置爲null,同時只顯示調用show,如果它不爲null – Sanjeev

回答

0

創建數組後,您無法調整其大小。您只能創建一個具有不同大小的新數組並複製非空元素。

您還可以設置元素null,只是忽略打印這些元素...

for (i = 0; i < c2; i++) { 
    if (c[i] != null) 
     c[i].Show(); 
} 

另一種方法是使用List,它允許你刪除元素。

或者,Map<String, Integer>可以使用從單詞到計數的映射。在這種情況下,你甚至都不需要Count類:

String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out"; 
StringTokenizer st = new StringTokenizer(s, " "); 

Map<String, Integer> map = new HashMap<>(); 

while (st.hasMoreTokens()) { 
    map.merge(st.nextToken(), 1, Integer::sum); 
} 

for (Map.Entry<String, Integer> e : map.entrySet()) { 
    System.out.print("Word= " + e.getKey()); 
    System.out.print(" Count= " + e.getValue()); 
    System.out.println(); 
}