闽江学院2015-2016学年下学期《软件测试》课程-第二次作业(个人作业)第一题

题目一:

1. 写一个Java程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);

2. 编写单元测试进行测试;

3. 用ElcEmma查看代码覆盖率,要求覆盖率达到100%。

代码:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;


public class Test1 {
 private HashMap< String, Integer > dictionary;
 private int wordsCount;
 public Test1() {
  dictionary = new HashMap< String, Integer >();
  wordsCount = 0;
 }
 public void insert( String word ) {
  if ( dictionary.containsKey( word ) ) {
   int currentCount = dictionary.get( word );
   dictionary.put( word, currentCount + 1 );
  } else {
   dictionary.put( word, 1 );
  }
  wordsCount++;
 }

 public int getDifferentWordsNum() {
  return dictionary.size();
 }

 public int getAllWordsNum() {
  return wordsCount;
 }

 public void displayDictionary() {
  for ( Iterator< String > it = dictionary.keySet().iterator(); it.hasNext(); ) {
   String key = it.next();
   System.out.print( key );
   System.out.print( ": " );
   System.out.println( dictionary.get( key ) );
  }
 }
 public static void main( String[] args ) throws Exception {
  String passage = "Hello World My First Unit Test";
  Scanner scanner = new Scanner( passage );
  Test1 dict = new Test1();
  while ( scanner.hasNextLine() ) {
   String line =scanner.nextLine();
   boolean isBlankLine = line.matches( "\W" ) || line.length() == 0;
   if ( isBlankLine ) {
    continue;
   }
   String[] words = line.split( "\W" );
   for ( String word : words ) {
    if ( word.length() != 0 ) {
     dict.insert( word );
    }
   }
  }
  dict.displayDictionary();
 }
}

运行截图:

代码覆盖率:

原文地址:https://www.cnblogs.com/GodEaterV/p/5342419.html