1.统计每个单词出现的次数
2.有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
3.打印格式:
to=3
think=1
you=2
//…
**=====================================================================**
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//创建HashMap
Map<String, Integer> map = new HashMap<>();
String str = "If you want to change your fate I think you must come to the dark horse to learn java";
//以空格“ ”为分隔符,将单词分割储存到数组strArr中
String[] strArr = str.split(" ");
//统计语句中的每个单词出现的次数
for (String s : strArr) {
if (!map.containsKey(s)) {//map.containsKey():判断map中是否存在所对应的key值
map.put(s, 1);
} else {
map.put(s, map.get(s) + 1);
}
}
//打印
System.out.println(map);
}
}
测试: