Reputation: 133
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
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';
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