0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 1
Car : 1
null : 1
Cat : 1
null : 1
Dog : 1
null : 1
代碼
import java.util.Arrays;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String w;
int count = -1;
while (str.hasMoreTokens()) {
count++;
w = str.nextToken();
word[count] = w;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int z = 0; z < 7; z++) {
if (Arrays.asList(unique).contains(word[z])) {
measure[z] += 1;
System.out.println(unique[z] + " : " + measure[z]);
}
}
}
}
是一個不是集合的數組? –
爲什麼你要使用這種方法,而不是使用'Map'? –
我編輯了我的問題。我想,爲了這樣做。 –