forked from Joyounger/Introduction-to-Java-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountEachLetter.java
More file actions
38 lines (27 loc) · 802 Bytes
/
CountEachLetter.java
File metadata and controls
38 lines (27 loc) · 802 Bytes
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
// date:17.3.31
// author: linyang <linyang@xiaomi.com>
// 统计字符串中每个字母
import javax.swing.JOptionPane;
public class CountEachLetter {
public static void main(String[] args) {
String s = JOptionPane.showInputDialog("enter a string");
int[] counts = countLetters(s.toLowerCase());
String output = "";
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
output += (char)('a' + i) + " appeas " +
counts[i] + ((counts[i] == 1)? " time\n" : " times\n");
}
}
JOptionPane.showMessageDialog(null, output);
}
public 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;
}
}