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中的對象數組中刪除對象
我會用[HashMap的(https://docs.oracle.com/javase/8/docs/api/java/util/HashMap的.html)。 – Fildor
HashMap非常適合您的場景,但是您可以將它們設置爲null,同時只顯示調用show,如果它不爲null – Sanjeev