سؤال

Here is a short program that counts the letters of any given word entered by the user. I'm trying to figure out what the following lines actually do in this program:

counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing

System.out.println((char)('a' + i) // I don't get what the 'a' + i actually does.

    import java.util.Scanner;

    public class Listing9_3 {

        public static void main(String[] args) {
            //Create a scanner
            Scanner input = new Scanner (System.in);
            System.out.println("Enter a word to find out the occurences of each letter: ");
            String s = input.nextLine();

            //Invoke the count Letters Method to count each letter
            int[] counts = countLetters(s.toLowerCase());

            //Display results
            for(int i = 0; i< counts.length; i++){
                if(counts[i] != 0)
                    System.out.println((char)('a' + i) + " appears " + 
                counts[i] + ((counts[i] == 1)? " time" : " times"));
    ***//I don't understand what the 'a' + i is doing
            }
        }
        public static int[] countLetters(String s) {
            int[] counts = new int [26]; // 26 letters in the alphabet

            for(int i = 0; i < s.length(); i++){
                if(Character.isLetter(s.charAt(i)))
                    counts[s.charAt(i) - 'a']++;   
  ***// I don't understand what the - 'a' is doin
            }
            return counts;
        }

    }
هل كانت مفيدة؟

المحلول

Characters are a kind of integer in Java; the integer is a number associated with the character on the Unicode chart. Thus, 'a' is actually the integer 97; 'b' is 98, and so on in sequence up through 'z'. So s.charAt(i) returns a character; assuming that it is a lower-case letter in the English alphabet, subtracting 'a' from it gives the result 0 for 'a', 1 for 'b', 2 for 'c', and so on.

You can see the first 4096 characters of the Unicode chart at http://en.wikibooks.org/wiki/Unicode/Character_reference/0000-0FFF (and there will be references to other pages of the chart as well). You'll see 'a' there as U+0061 (which is hex, = 97 decimal).

نصائح أخرى

Because you want your array to contains only the count of each letter from 'a' to 'z'.

So to index correctly each count of the letter within the array you would need a mapping letter -> index with 'a' -> 0, 'b' -> 1 to 'z' -> 25.

Each character is represented by a integer value on 16 bits (so from 0 to 65,535). You're only interested from the letters 'a' to 'z', which have respectively the values 97 and 122.

How would you get the mapping?

This can be done using the trick s.charAt(i) - 'a'.

This will ensure that the value returned by this operation is between 0 and 25 because you know that s.charAt(i) will return a character between 'a' and 'z' (you're converting the input of the user in lower case and using Character.isLetter)

Hence you got the desired mapping to count the occurences of each letter in the word.

On the other hand, (char)('a' + i) does the reverse operation. i varies from 0 to 25 and you respectively got the letters from 'a' to 'z'. You just need to cast the result of the addition to char otherwise you would see its unicode value be printed.

counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing 
assume charAT(i) is 'z'
now z-a will be equal to 25 (subtract the unicode / ASCII values).
so counts[25]=counts[25]+1;  // just keeps track of count of each character
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top