package LESSON11; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class exercise1 { /** 使用Scanner從控制台讀取一個字符串,統計字符串中每個字符出現的次數 */ public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("請輸入一個字符串"); String str=sc.nextLine(); char ch[]=str.toCharArray(); HashMap<Character, Integer> map=new HashMap(); // for (int i = 0; i < ch.length; i++) { // int count=1; // for (int j = i+1; j < ch.length; j++) { // if(ch[i]==ch[j]){ // count++; //這樣寫最后相同的鍵的值會被覆蓋,所有的value都為1 // } // // } // map.put(ch[i], count); // } //abcda int num=0; for (int i = 0; i < ch.length; i++) { if(!map.containsKey(ch[i])){//判斷集合中是否不包含某個字符 num=1; }else{ num=map.get(ch[i]);//獲取該字符已經出現的次數 num++; } map.put(ch[i], num);//每次循環都會存儲到map集合中 } System.out.println(map); } }
運行結果