源码:
//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 based 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