不错,半小时之内解题成功!
源码如下:
//Java how to program, 10th edition
//Exercise. 16.14: CharCount.java
//(Counting Letters) Modify the program of Fig. 16.18 to count the number of occurrences
// of each letter rather than of each word. For example, the string \"HELLO THERE\" contains two Hs, three
// Es, two Ls, one O, one T and one R. Display the results.
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;
public class CharCount
{
public static void main(String[] args)
{
// create HashMap to store String keys and Integer values
Map<String, Integer> myMap = new HashMap<>();
createMap(myMap); // create map d on user input
displayMap(myMap); // display map content
} // end main
// create map from user input
private static void createMap(Map<String, Integer> map)
{
Scanner scanner = new Scanner(System.in); // create scanner
System.out.println(\"Enter a string:\"); // prompt for user input
String input = scanner.nextLine();
// tokenize the input(将输入的字符串转换为字符数组)
char[] tokens = input.toCharArray();
// processing input text
for (char token : tokens)
{
// if the map contains the word (将字符数组中的字符转换为字符串,因为java.util.Map.put(String key, Integer value)中要求字符串数据类型)
if (map.containsKey(String.valueOf(token))) // is word in map
{
int count = map.get(String.valueOf(token)); // get current count
map.put(String.valueOf(token), count + 1); // increment count
}
else
map.put(String.valueOf(token), 1); // add new char with a count of 1 to map
}
scanner.close();
}
// display map content
private static void displayMap(Map<String, Integer> map)
{
Set<String> keys = map.keySet(); // get keys
// sort keys
TreeSet<String> sortedKeys = new TreeSet<>(keys);
System.out.printf(\"%nMap contains:%nKey\\t\\tValue%n\");
// generate output for each key in map
for (String key : sortedKeys)
System.out.printf(\"%-10s%10s%n\", key, map.get(key));
System.out.printf(
\"%nsize: %d%nisEmpty: %b%n\", map.size(), map.isEmpty());
}
} // end class
运行结果:
Enter a string:
Hello Pandeng, enjoy yourself in Java World!
Map contains:
Key Value
6
! 1
, 1
H 1
J 1
P 1
W 1
a 3
d 2
e 4
f 1
g 1
i 1
j 1
l 4
n 4
o 4
r 2
s 1
u 1
v 1
y 2
size: 22
isEmpty: false
Enter a string:
天行健,君子当自强不息;地势坤,君子以厚德载物
Map contains:
Key Value
不 1
以 1
健 1
势 1
厚 1
君 2
地 1
坤 1
天 1
子 2
强 1
当 1
德 1
息 1
物 1
自 1
行 1
载 1
, 2
; 1
size: 20
isEmpty: false
继续阅读与本文标签相同的文章
-
客服服务除了电话和工单还有哪些服务?阿里云服务方式整理
2026-05-18栏目: 教程
-
个人音视频常用工具介绍
2026-05-18栏目: 教程
-
用自定义监控实现 GPU 异常状况的检查与报警
2026-05-18栏目: 教程
-
与你同行,才能无障碍
2026-05-18栏目: 教程
-
分布式Id - redis方式
2026-05-18栏目: 教程
