(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”); (2)编写单元测试进行测试; (3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class test1 {
    // 统计结果用,采用Character即char做键(Key)
    private Map<Character, Integer> countMap = new HashMap<Character, Integer>();
    public void countChar(String str) {
        char[] chars = str.toCharArray();// 将字符串转换成字符char数组
        // 循环,开始统计
        for (char ch : chars) {
            // 判断字符是否存在
            if (!countMap.containsKey(ch)) {
                // 不存在,在Map中加一个,并设置初始值为0
                countMap.put(ch, 0);
            }
            // 计数,将值+1
            int count = countMap.get(ch);
            countMap.put(ch, count + 1);
        }
        // 输出结果
        Set<Character> keys = countMap.keySet();
        for(Character ch : keys){
            System.out.println("字符" + ch + "出现次数:" + countMap.get(ch));
        }
}
    public static void main(String[] args) {
 
        test1 test = new test1();
        test.countChar("Hello World My First Unit Test");
    }
}
单元测试代码:
import org.junit.Test;
import junit.framework.TestCase;
public class test1Test  {
@Test 
public void test() throws Exception {
    // 测试方法
    test1 test = new test1();
    test.countChar("Hello World My First Unit Test"); // 注:不支持中文
}
}
                    
                
                
            
        
浙公网安备 33010602011771号