1.
(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
(2)编写单元测试进行测试;
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
步骤:
(1)
package cn.wang;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Test1 {
public void test(){
String str = "Hello World My First Unit Test";
String[] items = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : items) {
if (map.containsKey(s))
map.put(s, map.get(s) + 1);
else {
map.put(s, 1);
}
}
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> entry : map.entrySet()) {
list.add(entry);
}
//Collections.sort(list, new EntryComparator());
for (Entry<String, Integer> obj : list) {
System.out.println("单词:"+obj.getKey() + "\t" +"出现:"+ obj.getValue());
}
}
}
(2)
package cn.wang;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class WordFreq {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.test();
}
}
(3)单元测试:
package cn.wang;
import static org.junit.Assert.*;
import org.junit.Test;
public class Word {
@Test
public void test() {
String Str = "Hello World My First Unit Test";
}
}
3.覆盖率:
2.
(1)把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;
(2)编写单元测试进行测试;
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
步骤:
(1)编写一个方法类:
package cn.wang;
import java.util.Scanner;
public class Test {
public void test(){
Scanner input = new Scanner(System.in);
System.out.print("请输入英文:");
String str = input.nextLine();
String[] strArr = str.split("\\s+|[,]");
StringBuffer result = new StringBuffer();
for(int i = strArr.length -1;i >=0; i--){
result.append(strArr[i] + " ");
}
result.setCharAt(str.length()-0, (char) 0);
System.out.println("颠倒顺序后的结果为:"+result.toString());
}
}
(2)实例化这个方法:
package cn.wang;
import java.util.Scanner;
public class Text{
public static void main(String[] args){
Test test = new Test();
test.test();
}
}
2.单元测试:
package cn.wang;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestRun {
@Test
public void test() {
String str = "how are you";
}
}
3.输出结果:
(4)覆盖率: