第六题
手动输入一个字符串,仅限小写字母,统计并输出每个字符在字符串中出现的次数,并输出。提示(可以用Map)。
实例:
输入:aaabbbccc
输出:
a 3
b 3
c 3
import java.util.HashMap;
import java.util.Map;
/**
* 手动输入一个字符串,仅限小写字母,统计并输出每个字符在字符串中出现的次数,并输出。提示(可以用Map)
* 实例:
* 输入:aaabbbccc
* 输出:a 3
* b 3
* c 3
* @author lx
*
*/
public class Test {
public static void main(String[] args) {
Map<Character, Integer> map = count("aAaabbbccc");
map.forEach((k, v) -> {
if (map.containsKey('#')) {
System.out.println("请正确输入仅限小写字母的字符串");
} else {
System.out.println(k + " " + v);
}
});
}
public static Map<Character, Integer> count(String strIn) {
// 返回结果的map
Map<Character, Integer> resultMap = new HashMap<Character, Integer>();
// 限制字符串为小写字母
for (int i = 0; i < strIn.length(); i++) {
if (strIn.charAt(i) > 'z' || strIn.charAt(i) < 'a') {
resultMap.put('#', 1);
return resultMap;
}
}
// 统计每个字符在字符串中出现的次数
for (int i = 0; i < strIn.length(); i++) {
Integer integer = resultMap.get(strIn.charAt(i));
resultMap.put(strIn.charAt(i), integer == null ? 1 : integer + 1);
}
return resultMap;
}
}