當前位置:成語大全網 - 新華字典 - java程序:統計壹段英文段落中每個單詞出現的次數,這個段落存儲在壹個字符串變量中

java程序:統計壹段英文段落中每個單詞出現的次數,這個段落存儲在壹個字符串變量中

import java.util.HashMap;

import java.util.Iterator;

import java.util.Scanner;

/**

* 字典類,記錄文章中出現過的所有單詞及其次數

* @author Administrator

*

*/

public class Dictionary {

private HashMap< String, Integer > dictionary;

private int wordsCount;

/**

* 字典這個類的構造函數

*/

public Dictionary() {

dictionary = new HashMap< String, Integer >();

wordsCount = 0;

}

/**

* 向字典裏插入壹個單詞

* @param word

*/

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++;

}

/**

* 取得字典裏所有不同的單詞

* @return

*/

public int getDifferentWordsNum() {

return dictionary.size();

}

/**

* 返回字典裏的所有單詞 * 其出現次數

* @return

*/

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 = "public static void main( String[] args ) {";

Scanner scanner = new Scanner( passage );

Dictionary dict = new Dictionary();

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

}

}