初学Java 数组统计字母
1 public class CountLetterInArray { 2 public static void main(String[] args) { 3 char[] chars = createArray(); 4 5 System.out.println("The lowercase letters are: "); 6 displayArray(chars); 7 8 int[] counts = countLetters(chars); 9 10 System.out.println(" "); 11 System.out.println("The occurrences of each letter are: "); 12 displayCounts(counts); 13 } 14 15 public static char[] createArray() { 16 char[] chars = new char[100]; 17 for(int i=0; i<chars.length; i++) { 18 chars[i] = RandomCharacter.getRandomLowerCaseLetter(); 19 } 20 return chars; 21 22 } 23 public static void displayArray(char[] chars) { 24 for(int i=0; i<chars.length; i++) { 25 if((i+1)%20==0) 26 System.out.println(chars[i]); 27 else 28 System.out.print(chars[i]+" "); 29 } 30 } 31 public static int[] countLetters(char[] chars) { 32 int[] counts = new int[26]; 33 34 for(int i=0; i<chars.length; i++) { 35 counts[chars[i]-'a']++; 36 } 37 return counts; 38 } 39 public static void displayCounts(int[] counts) { 40 for(int i=0; i<counts.length; i++) { 41 if((i+1)%10==0) 42 System.out.println(counts[i]+" "+(char)(i+'a')); 43 else 44 System.out.print(counts[i]+" "+(char)(i+'a')+" "); 45 } 46 } 47 }