-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountLetters.java
More file actions
41 lines (35 loc) · 1.16 KB
/
CountLetters.java
File metadata and controls
41 lines (35 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
// ****************************************************************
// CountLetters.java
//
// Reads a words from the standard input and prints the number of
// occurrences of each letter in that word.
//
// ****************************************************************
public class CountLetters {
public static void main(String[] args) {
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
//get word from user
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
//convert to all upper case
word = word.toUpperCase();
//count frequency of each letter in string
for (int i=0; i < word.length(); i++) {
try{
counts[word.charAt(i)-'A']++;
}
catch (ArrayIndexOutOfBoundsException problem) {
System.out.println("Contained characters other than letters, character was: " + (char)(Integer.parseInt(problem.getMessage()) + 'A'));
}
}
//print frequencies
System.out.println();
for (int i=0; i < counts.length; i++) {
if (counts [i] != 0) {
System.out.println((char)(i +'A') + ": " + counts[i]);
}
}
}
}