給定一個字符數組,統計字符數組中每一個字符出現的次數,並打印到控制檯

  • 
    /*
    統計字符出現的個數
     */
    public class TuoZhan03 {
        public static void main(String[] args) {
            char [] arr = {'a','l','f','m','f','o','b','b','s','n'};
            printCount(arr);
        }
        public static void printCount(char [] arr){
            for(int i =0; i< arr.length;i++){         //排序算法
                for (int j = 1;j<=arr.length - 1-i;j++){
                    if(arr[j] < arr[j-1]){
                        char temp =  arr[j];
                        arr[j] = arr[j-1];
                        arr[j-1] = temp;
                    }
                }
            }
            int count = 0;              //計數器
            char temp = arr[0];         //存儲臨時變量,目的只存在一個
            for (int i = 0;i<arr.length;i++){
                if( temp == arr[i]){
                    count ++;
                    if(i == arr.length -1){                  //輸出最後一個元素
                        System.out.println(arr[i]+"--->"+ count);
                    }
                }else{
                    System.out.println(arr[i-1]+"--->"+ count);
                    count = 0;              //歸零
                    temp = arr[i];          //重新定義臨時變量
                    i-=1;
                }
            }
        }
    }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章