本题目要求读入一个字符串,统计字符串中每个字符出现的次数,输出现次数最多(输入的数据中,出现次数最多的字符唯一)的字符以及次数。
在这里给出一组输入。例如:
import java.util.Scanner;
import java.util.*;
public class Day4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<Character,Integer> ma=new HashMap<>();
String str=sc.nextLine();
int max=0;
char chmax=' ';
for(int i=0;i<str.length();i++){
char ch=str.charAt(i); //从头开始获取字符
if(ma.containsKey(ch)){ //检查 hashMap 中是否存在指定的 key
ma.replace(ch,ma.get(ch)+1); //如果存在就更新当前的key对应的value值
}
else{ //如果不存在就把当前的key和value添加到hashMap中
ma.put(ch,1);
}
if(ma.get(ch)>max){ //如果当前key对应的value值大于最大值,更新max和chmax
max=ma.get(ch);
chmax=ch;
}
}
System.out.print(chmax+","+max);
}
}