1 //通過Map 類實現,通過鍵值對的方式,可以將輸入的字符串的每一個字符,作為鍵,每個字符出現的次數作為值:如下: 2 3 public class Find { 4 public static void main(String[] args){ 5 String scan=new Scanner(System.in).nextLine();//獲取鍵盤上輸入的字符串; 6 Map<Character,Integer> map = new HashMap<Character,Integer>();//新建一個HashMap對象; 7 //通過FOR循環,把String的鍵值存放到map 8 for(int i=0;i<scan.length();i++){ 9 char temp=scan.charAt(i);//通過循環,找到字符串的每一位字符並存入到temp中; 10 if(map.containsKey(temp)){//如果map里面有temp這個字符 11 map.put(temp, map.get(temp)+1);//把temp的值加1; 12 }else{//如果map里面沒有temp這個字符, 13 map.put(temp, 1);//把temp的值設為1; 14 } 15 } 16 /*Collection c = map.entrySet(); 17 Iterator it = c.iterator(); 18 Map.Entry<Character, Integer> entry; 19 while(it.hasNext()){ 20 entry = (Map.Entry<Character, Integer>) it.next(); 21 } 22 */ 23 int maxnum = Collections.max(map.values());//調用Collections類的max方法,獲取map的值的集合;並找出最大的那個值; 24 Set<Character> set = new HashSet<Character>();//建立一個set對象 25 for(Map.Entry<Character, Integer> entry1:map.entrySet()){ //通過集合的循環,把map的值放到entry1里,通過entry1找到值最大的maxnum的key; 26 if(entry1.getValue()==maxnum){ 27 set.add(entry1.getKey()); 28 } 29 } 30 System.out.println("出現次數最多的字母為:"+set+" 最多出現次數為"+maxnum); 31 32 } 33 34 }