Demo类:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Demo {
public void countWord(String str) {
String[] wordsArray = str.split(" ");
Map wordsMap = new HashMap();
for (String word : wordsArray) {
if (wordsMap.containsKey(word)) {
wordsMap.put(word, wordsMap.get(word) + 1);
} else {
wordsMap.put(word, 1);
}
}
Set setKey = wordsMap.keySet();
Iterator itKey = setKey.iterator();
while (itKey.hasNext()) {
String word = itKey.next().toString();
int count = wordsMap.get(word);
System.out.println("单词 " + word + " 出现" + count + "次");
}
}
}
DemoTest:
import static org.junit.Assert.*;
import org.junit.Test;
public class DemoTest {
@Test
public void testCountWord() {
Demo demo = new Demo();
demo.countWord("Hello World My First Unit Test");
}
}