问题1
package cn.zhao.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class testq1 {
public void countWord(String str) {
String[] wordsArray = str.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (String word : wordsArray) {
if (wordsMap.containsKey(word)) {
wordsMap.put(word, wordsMap.get(word) + 1);
} else {
wordsMap.put(word, 1);
}
}
Set<String> setKey = wordsMap.keySet();
Iterator<String> itKey = setKey.iterator();
while (itKey.hasNext()) {
String word = itKey.next().toString();
int count = wordsMap.get(word);
System.out.println("单词 " + word + " 出现" + count + "次");
}
}
}
JUNIT测试
package cn.zhao.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class testq1Test {
@Test
public void testCountWord() {
testq1 q1 = new testq1();
q1.countWord("Hello World My First Unit Test Test");
}
}
截图如下