Created
May 4, 2013 05:48
-
-
Save jimmy087/5516367 to your computer and use it in GitHub Desktop.
Count each letter in the string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class CountEachLetter { | |
| public static void main(String[] args) { | |
| java.util.Scanner input = new java.util.Scanner(System.in); | |
| System.out.println("Please enter the string: "); | |
| String s = input.nextLine(); | |
| // Invoke the countLetters 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.")); | |
| } | |
| } | |
| } | |
| // Count each letter in the string | |
| private static int[] countLetters(String s) { | |
| int [] counts = new int[26]; | |
| for (int i = 0; i < s.length(); i++) { | |
| if (Character.isLetter(s.charAt(i))) { | |
| counts [s.charAt(i) - 'a']++; | |
| } | |
| } | |
| return counts; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment