软件测试实验二
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了软件测试实验二相关的知识,希望对你有一定的参考价值。
(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
FileWoedCount:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class FileWordCount {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
String s;
StringBuffer sb = new StringBuffer();
while ((s = br.readLine()) != null) {
sb.append(s);
}
Map<String,Integer> map = new HashMap<String, Integer>();
StringTokenizer st = new StringTokenizer(sb.toString(),",.! \n");
while (st.hasMoreTokens()) {
String letter = st.nextToken();
int count;
if (map.get(letter) == null) {
count = 1;
} else {
count = map.get(letter).intValue() + 1;
}
map.put(letter,count);
}
Set<WordEntity> set = new TreeSet<WordEntity>();
for (String key : map.keySet()) {
set.add(new WordEntity(key,map.get(key)));
}
// 自己拼接字符串,输出想要的字符串格式
System.out.println("输出形式一:");
for (Iterator<WordEntity> it = set.iterator(); it.hasNext(); ) {
WordEntity w = it.next();
System.out.println("单词:" + w.getKey() + " 出现的次数为: " + w.getCount());
}
// 直接打印 WordEntity 对象,实现我们想要的输出效果,只需在WordEntity类中重写toString()方法
System.out.println("输出形式二:");
for (Iterator<WordEntity> it = set.iterator(); it.hasNext(); ) {
WordEntity w = it.next();
System.out.println(w);
}
// 我们可以控制只输出前三名来
System.out.println("输出形式三:");
int count = 1;
for (Iterator<WordEntity> it = set.iterator(); it.hasNext(); ) {
WordEntity w = it.next();
System.out.println("第" + count + "名为单词:" + w.getKey() + " 出现的次数为: "
+ w.getCount());
if (count == 3)// 当输出3个后跳出循环
break;
count++;
}
} catch (FileNotFoundException e) {
System.out.println("文件未找到~!");
} catch (IOException e) {
System.out.println("文件读异常~!");
}
}
}
FileWordCountTest:
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
public class FileWordCountTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
}
WordEntity:
public class WordEntity implements Comparable<WordEntity> {
private String key;
private Integer count;
public WordEntity (String key, Integer count) {
this.key = key;
this.count = count;
}
public int compareTo(WordEntity o) {
int cmp = count.intValue() - o.count.intValue();
return (cmp == 0 ? key.compareTo(o.key) : -cmp);
//只需在这儿加一个负号就可以决定是升序还是降序排列 -cmp降序排列,cmp升序排列
//因为TreeSet会调用WorkForMap的compareTo方法来决定自己的排序
}
@Override
public String toString() {
return key + " 出现的次数为:" + count;
}
public String getKey() {
return key;
}
public Integer getCount() {
return count;
}
}
以上是关于软件测试实验二的主要内容,如果未能解决你的问题,请参考以下文章