(1)寫一個程序,用於分析一個字符串中各個單詞出現的頻率,並將單詞和它出現的頻率輸出顯示。(單詞之間用空格隔開,如「Hello World My First Unit Test」); (2)編寫單元測

import java.util.HashMap;java

import java.util.Iterator;數組

import java.util.Map;this

import java.util.Set;rem

 

 

    public class WordsFreq {字符串

                 

        private Map<String,Integer> wordsMap;get

        public  WordsFreq (String strWords){it

 

         wordsMap=this.getArray(strWords);class

    }test

        //拆分字符串,放入數組,統計數組中相同單詞的個數,並放入鍵值對數組中import

        private Map<String, Integer> getArray(String strWords) {

            // TODO Auto-generated method stub

            String[] words_Array=strWords.split("");

            Map<String,Integer>words_Map=new HashMap<String,Integer>();

            int arrLength=words_Array.length;

            for (int i=0;i<arrLength;i++){

                if(!words_Map.containsKey(words_Array[i])){

                    words_Map.put(words_Array[i],1);

                }

                else{

                    int currentNum=words_Map.get(words_Array[i])+1;

                    words_Map.remove(words_Array[i]);

                    words_Map.put(words_Array[i], currentNum);

                }

            }

            return words_Map;

                  

        }

        //輸出結果

        public void OutputResult(){

            Set s=wordsMap.keySet();

            Iterator i=s.iterator();

            while(i.hasNext()){

                Object o=i.next();

                System.out.println(o+"出現了"+wordsMap.get(o)+"次");

            }

        }

 

    }

 

 

import static org.junit.Assert.*;

 

import org.junit.Before;

import org.junit.Test;

 

 

public class WordsFreqTest {

 

 

    @Test

    public void test() {

       

         WordsFreq word=new WordsFreq("Hello World My First Unit Test");

         word.OutputResult();

 

}}

相關文章
相關標籤/搜索