package cn.itcast.demo24;
import java.util.HashMap;
/*
* 用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you
must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)
*/
public class Demo22 {
public static void main(String[] args) {
String s = "If you want to change your fate I think you " +
"must come to the dark horse to learn java";
get(s);
}
public static void get(String s){
String[] str = s.split(" ");
HashMap<String, Integer> map = new HashMap<>();
for(String ss:str){
Integer num = map.get(ss);
if(num==null){
map.put(ss, 1);
}else {
map.put(ss, ++num); ...................... //此处如果写为 map.put(ss,num++),就会错误,
//否则就写为 num++;
// map.put(ss,num);
}
}
System.out.println(map);
Integer num = map.get(ss);
if(num==null){
num = 1;
}else {
num++;
}
map.put(ss,num);
*/
}
import java.util.HashMap;
/*
* 用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you
must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)
*/
public class Demo22 {
public static void main(String[] args) {
String s = "If you want to change your fate I think you " +
"must come to the dark horse to learn java";
get(s);
}
public static void get(String s){
String[] str = s.split(" ");
HashMap<String, Integer> map = new HashMap<>();
for(String ss:str){
Integer num = map.get(ss);
if(num==null){
map.put(ss, 1);
}else {
map.put(ss, ++num); ...................... //此处如果写为 map.put(ss,num++),就会错误,
//否则就写为 num++;
// map.put(ss,num);
}
}
System.out.println(map);
}
下面这样写也可以
/*for(String ss:str){Integer num = map.get(ss);
if(num==null){
num = 1;
}else {
num++;
}
map.put(ss,num);
*/
}