黑马程序员技术交流社区
标题:
map
[打印本页]
作者:
weidong10heima
时间:
2016-7-10 23:59
标题:
map
分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
作者:
weidong10heima
时间:
2016-7-11 00:15
package com.weidong.homework;
//--------录入--------------------------------------------
//导包
//创建对象
//调用方法
//--------步骤--------------------------------------------
//创建集合对象
//创建元素对象
//将元素放到集合中
//迭代集合//返回所有键的集合
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class Test3 {
public static void main(String[] args) {
//创建一个Scanner对象,用于接收键盘输入的字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入一串字符转:");
String enterStr = sc.nextLine();
//--------步骤--------------------------------------------
//创建集合对象
HashMap<Character, Integer> mapping = new HashMap<Character, Integer>();
//------将字符串转为字符数组
char[] chs = enterStr.toCharArray();
//创建元素对象
for (char ch : chs) {
if ((ch >='A' && ch <='Z')||(ch >='a' && ch <='z'||ch =='-'||ch =='~')) {
Integer num = mapping.get(ch);
if (num == null) {
//将元素放到集合中
mapping.put(ch, 1);
}else {
//将元素放到集合中
num++;
mapping.put(ch, num);
}
}
}
//迭代集合//返回所有键的集合
Set<Entry<Character, Integer>> sset = mapping.entrySet();
for (Entry<Character, Integer> entry : sset) {
System.out.print(entry.getKey() + "(" + entry.getValue() + ")");
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2