源码:
//Exercise 16.16: DuplicateWordCount.java
//16.16 (Counting Duplicate Words) Write a program that determines and prints the number of
//duplicate words in a sentence. Treat uppercase and lowercase letters the same. Ignore punctuation.
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;
public class DuplicateWordCount
{
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
String[] tokens = input.split(\" \");
// processing input text
for (String token : tokens)
{
String word = token.toLowerCase(); // get lowercase word
// if the map contains the word
if (map.containsKey(word)) // is word in map
{
int count = map.get(word); // get current count
map.put(word, count + 1); // increment count
}
else
map.put(word, 1); // add new word 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
int duplicateWords = 0;
// 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)
{ if (map.get(key)>1)
{ duplicateWords ++;
System.out.printf(\"%-10s%10s%n\", key, map.get(key));
}
}
System.out.printf(
\"%nDuplicate Words: %d%n\", duplicateWords);
}
} // end class
运行结果:
Enter a string:
高 桌子 低 桌子 都是 桌子 他 大舅 他 二舅 都是 他舅
Map contains:
Key Value
他 2
桌子 3
都是 2
Duplicate Words: 3
继续阅读与本文标签相同的文章
上一篇 :
2007北京市小学生程序设计友谊赛详细答案
下一篇 :
北京移动5G套餐资费出炉 不换卡不换号169元起
-
阿里云910会员节:开启时光机领会员大礼包,云产品满减优惠活动
2026-05-18栏目: 教程
-
基于宜搭的“报表分析”实践案例
2026-05-18栏目: 教程
-
javascript教程:实现函数柯里化与反柯里化
2026-05-18栏目: 教程
-
基于宜搭的“定时消息通知”实践案例
2026-05-18栏目: 教程
-
AIoT入门:用虚拟设备体验物联网平台设备上云&设备数据存储
2026-05-18栏目: 教程
