Problem Description
命令行输入一个由数字组成的任意字符串,统计出每个数字出现的次数。
Input Description
1239586838
Output Description
0 counts:0
1 counts:1
2 counts:1
3 counts:2
4 counts:0
5 counts:1
6 counts:1
7 counts:0
8 counts:3
9 counts:1
我的想法:
我的代码:
import java.util.*;
import java.util.function.BiConsumer;
class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split("");
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i <= 9; i++) {
map.put(i, 0);
}
for (String s1 : s) {
int key = Integer.parseInt(s1);
if(key < 0 || key > 9){
continue;
}
int value = map.get(Integer.parseInt(s1));
map.put(key, value + 1);
}
map.forEach(new BiConsumer<Integer, Integer>() {
@Override
public void accept(Integer integer, Integer integer2) {
System.out.println(integer + " counts:" + integer2);
}
});
}
}