码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-31 20:28:26      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

题目一:

 

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();
 }
}

运行截图:

技术分享

代码覆盖率:技术分享

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!