问题: 统计一段句子中各单词出现的次数.
思路:
1, 使用 split 方法将文章进行分割, 我们这里以空格, 逗号和句点为分隔符, 然后存到一个字符串数组中.
2, 创建一个 hashMap 集合, key 是字符串类型, 保存单词; value 是数字类型, 保存该单词出现的次数.
3, 遍历思路 1 中的字符串数组, 如果 key(单词) 没有出现过, map 中增加一个元素, key 为该单词, 定义 value 为 1; 如果 key(单词) 出现过, 那么 value 的值加 1.
4. 遍历输入 key 及其对应的 value 值.
具体代码如下:
StrList 类, 实现统计单词出现次数的方法.
- package wordCounts;
- import java.util.HashMap;
- import java.util.Map.Entry;
- public class StrList {
- public String StatList(String s) {
- StringBuffer sb = new StringBuffer();
- HashMap<String, Integer> has = new HashMap<String,Integer>();// 打开哈希表, 字符类型储存 key(单词), 整型储存 value(单词出现的次数)
- String[] sList = s.split("|,|\\.");// 使用 split 方法将字符串 s 按空格, 逗号和句点分割开, 并存在字符数组 sList 中
- for(int i=0; i<sList.length; i++){
- // 遍历 sList 数组
- if(!has.containsKey(sList[i])){
- // 如果没有这个单词, 就将单词存入 key 里, value 值为 1;containsKey 方法 判断集合中是否包含指定的 key
- has.put(sList[i], 1);
- }else{
- // 如果已经存在, 就将 value 值加 1; 用 get 方法获取 key 对应的 value 值
- has.put(sList[i], has.get(sList[i])+1);
- }
- }
- // 使用增强 for 循环遍历, 通过 Entry 集合访问, 可以访问 key 及其对应的 Value 值
- for(Entry<String, Integer> entry:has.entrySet()){
- System.out.println(entry.getKey()+":"+entry.getValue());
- }
- return sb.toString();
- }
- }
main 方法 (创建另一个类):
方式一: 已经指定好了句子
- package wordCounts;
- import java.util.Scanner;
- public class WordCounts{
- public static void main(String[] args) {
- String sentence = "The most distant way in the world,"
- + "is not the way from birth to the end."
- + "It is when I stand in front of you,"
- + "but you don't understand I love you.";
- System.out.println(StatList(sentence));
- }
- }
方式二: 从键盘输入
- package wordCounts;
- import java.util.Scanner;
- public class WordCounts{
- public static void main(String[] args) {
- @SuppressWarnings("resource")
- Scanner scanner = new Scanner(System.in);
- String ab = scanner.nextLine();
- StrList sl = new StrList();
- System.out.println(sl.StatList(ab));
- }
- }
- ----------------
来源: http://www.bubuko.com/infodetail-3302995.html