Ramsey
Ramsey

Reputation: 133

Count Letter Frequencies

The below code is from my old lecture notes and I have forgotten why do we need letters[index]++ here? Can someone explain why do we need it?

public class CountLetterFrequencies {

    /* Private instance variables */
    private static int[] letters = new int[26];

    public static void main(String[] args) {
        System.out.println("This program counts letter frequencies. Enter text:");

        Scanner sc = new Scanner(System.in);

        String line = sc.nextLine(); 

        countLetterFrequencies(line);

        printFrequencyTable();

        sc.close();
    }

    /* Counts the letter frequencies in a line of text */
    private static void countLetterFrequencies(String line) {
        for (int i = 0; i < line.length(); i++) {
            char ch = line.charAt(i);
            if (Character.isLetter(ch)) { // Character.isLetter(ch)
                int index = Character.toUpperCase(ch) - 'A'; // index = C - A = 2
                letters[index]++;
            }
        }
    }

private static void printFrequencyTable() {
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            int index = ch - 'A'; // So, if ch is B, then index => B-A => 1
            if(letters[index] != 0) // if we wanna print only existing letters
                System.out.println(ch + ": " + letters[index]);
        }
    }

}

Upvotes: 2

Views: 97

Answers (1)

Alexia Desouza
Alexia Desouza

Reputation: 393

 int index = Character.toUpperCase(ch) - 'A'; 

index gives you the position in the array where the count for that particular is stored.

letters[index]++;

And then it increments the count of that particular character.

Understand this

 index = Character.toUpperCase(ch) - 'A';
  • 'A' - 'A' this will give array position 0
  • 'B' - 'A' this will give array position 1 which is B count position and so on, till
  • 'Z' - 'A' this will give position 25 of the array where the count of 'Z' will be stored

It does ASCII value subtraction

For

 'A' - 'A' it will do 65-65 =0    65 is ascii value of 'A'

 'B' - 'A' it will do 66-65 =1

 'Z' - 'A' it will do 90-65 = 25

Upvotes: 3

Related Questions