解决思路:第一步:将输入的字符串转换成字符数组
第二步:循环读取数组,并Map键值对的形式去存储对应的字符和出现的次数
第三步:定义两个临时变量,一个用来存储出现最多次数字符,一个是用来存储出现的次数
具体实现代码如下:
public class Test_One {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String input=scan.next();
char[] ch=input.toCharArray();
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
for(char a:ch)
{
if(map.get(a) != null)
{
map.put(a, map.get(a)+1);
}
else
{
map.put(a, 1);
}
}
System.out.println("输入次数最多的字符为:"+getMaxNumChar(map)+",总共出现了:"+map.get(getMaxNumChar(map)));
System.out.println("输入次数最多的字符为:"+getMaxNumChar2(map)+",总共出现了:"+map.get(getMaxNumChar2(map)));
System.out.println(map);
}
//以Entry的方式去获取map对象中的值
public static Character getMaxNumChar(Map<Character,Integer> map)
{
Integer maxNum=0;
Character ch=null;
Set<Entry<Character,Integer>> set=map.entrySet();
Iterator<Entry<Character,Integer>> it=set.iterator();
while(it.hasNext())
{
Entry<Character,Integer> entry=it.next();
Character key=entry.getKey();
Integer value=entry.getValue();
if(value > maxNum)
{
ch=key;
maxNum=value;
}
}
return ch;
}
public static Character getMaxNumChar2(HashMap<Character,Integer> map)
{
Integer maxNum=0;
Character charact=null;
Set<Character> set=map.keySet();
Iterator<Character> it=set.iterator();
while(it.hasNext())
{
Character ch=it.next();
Integer value=map.get(ch);
if(value > maxNum)
{
charact=ch;
maxNum=value;
}
}
return charact;
}
}
由此代码衍生出的知识点:Map键值对的取值方法
个人认为总的分为两大类:1、通过加强for循环去取值(一种是直接去keySet集合,另外一种是直接取entrySet) 2、通过迭代器去取值(一种是直接去取keySet集合另外一种也是通过键值对的方式去取集合)
定义map集合数据如下:
HashMap<String,String> map=new HashMap<String,String>();
map.put("aa", "AA");
map.put("bb", "BB");
map.put("cc", "CC");
map.put("dd", "DD");
map.put("ee", "EE");
map.put("ff", "FF");
map.put("gg", "GG");
第一种:通过加强for循环去取值
for(String key:map.keySet())
{
System.out.println("输入的键为:"+key+",对应的值为:"+map.get(key));
}
for(Entry<String,String> entry:map.entrySet())
{
System.out.println("输入的键为:"+entry.getKey()+",对应的值为:"+entry.getValue());
}
第二种:通过迭代器取值
Set<String> set=map.keySet();
Iterator<String> it=set.iterator();
while(it.hasNext())
{
String key=it.next();
System.out.println(key+":"+map.get(key));
}
Set<Entry<String, String>> set1= map.entrySet();
Iterator<Entry<String, String>> it1=set1.iterator();
while(it1.hasNext())
{
Entry<String,String> entry=it1.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}