CountLetterInArray

来源:互联网 发布:ping测试网络 编辑:程序博客网 时间:2024/04/27 15:46
public class CountLetterInArray {
    public static void main(String[] args) {
        //Declare and create an array
        char[] chars = createArray();
        
        System.out.println("The lowercase letters are:");
        //Display the array
        displayArray(chars);
        
        
        System.out.println("\n\nThe occurrences of each " +
                "letter are:");
        //Display counts
        displayCounts(chars);
        
        
        
    }
    
    //Create an array of characters
    static char[] createArray() {
        char[] chars = new char[100];
        for(int i=0; i < chars.length; i++)
            chars[i] =
            getRandomLowerCaseLetter();
        return chars;
    }
    
    //Display the array of characters
    static void displayArray(char[] chars) {
        for(int i =0; i < chars.length; i++) {
            if(i % 20 == 0)
                System.out.printf("\n%2c", chars[i]);
            else
                System.out.printf("%2c", chars[i]);
        }
    }
    
    //Display counts
    static void displayCounts(char[] chars) {
        int[] counts = countLetters(chars);
        for(int i = 0; i < 26; i++)
            if(i % 7 == 0)
                System.out.printf("\n%3d%2c", counts[i], 'a' + i);
            else System.out.printf("%3d%2c", counts[i], 'a' + i);
    }
    
    //Count the occurrences of each letter
    static int[] countLetters(char[] chars) {
        int[] counts = new int[26];
        for(int i = 0; i < chars.length; i++)
            counts[chars[i] - 'a']++;
        return counts;
    }
    
    //Get random lower case letter
    static char getRandomLowerCaseLetter() {
        return (char) (Math.random() * 26 + 'a');
    }
    
}







The lowercase letters are:

 s w h d i z v w k d p n k z g g x p u j
 c i u o e b g h v t h g k a s n w e h x
 z r c t s p l n y t e l l b l o a t i i
 g l h n y o l l n k y v t c w u t h b n
 y a g v i q i g u z g k e o h w k s n m

The occurrences of each letter are:

  3 a  3 b  3 c  2 d  4 e  0 f  8 g
  7 h  6 i  1 j  6 k  7 l  1 m  7 n
  4 o  3 p  1 q  1 r  4 s  6 t  4 u
  4 v  5 w  2 x  4 y  4 z

0 0
原创粉丝点击