1.利用map统计字符串中 字符出现的次数
System.out.println("请输出一段英文:");
//从键盘获取
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
//创建集合
HashMap<Character, Integer> map = new HashMap<>();
//循环
for (int i = 0; i < line.length();i++) {
char key = line.charAt(i);//获取字符
Integer count = map.get(key);//获取map里 键key 的值 并赋给 count(出现的次数)
if (null == count){//如果是空 就记为出现一次
map.put(key,1);
}else {//如果不是空 就加一次
map.put(key,++count);
}
}
Set<Character> characters = map.keySet();//获取键的集合
for (Character key : characters) {
System.out.println(key + ":" + map.get(key) + "个");
}
2.斗地主
HashMap<Integer, String> card = new HashMap<>();//扑克牌
ArrayList<Integer> indexList = new ArrayList<>();//索引
String[] colors = {"♥","♠","♦","♣"};
String[] nums = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//将花色和点数 组织好 放到扑克牌里
int index = 0;
for (String num : nums){
for (String color : colors){
card.put(index,color+num);//组装扑克牌
indexList.add(index++);//索引
}
}
//大小王单独处理
card.put(index,"¥");
indexList.add(index);
card.put(++index,"$");
indexList.add(index);
//洗牌
Collections.shuffle(indexList);
//定义玩家
TreeSet<Integer> p1 = new TreeSet<>();
TreeSet<Integer> p2 = new TreeSet<>();
TreeSet<Integer> p3 = new TreeSet<>();
//底牌
TreeSet<Integer> lastCard = new TreeSet<>();
//发牌
for (int i = 0; i < indexList.size(); i++) {
if ( i >= indexList.size()-3 ){
lastCard.add(indexList.get(i));
}else {
switch ( i % 3 ){
case 0:
p1.add(indexList.get(i));
break;
case 1:
p2.add(indexList.get(i));
break;
case 2:
p3.add(indexList.get(i));
break;
}
}
}
//看牌
showCard("涅尘",p1,card);
showCard("美娜",p2,card);
showCard("科比",p3,card);
showCard("底牌",lastCard,card);
}
private static void showCard(String name, TreeSet<Integer> type, HashMap<Integer, String> card) {
System.out.print(name + ":");
for (Integer index : type){
System.out.print(card.get(index)+" ");
}
System.out.println("\n");