11章-练习20-Map元音出现次数


import java.util.*;

/*
* 练习20:修改练习16,使得你可以跟踪每一个元音字母出现的次数
*/
public class Exercise16 {

public static void main(String[] args) {

Set<Character> vowelWord = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));

Map<Character, Integer> vowelExistMap = new HashMap<>();

Set<String> words = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
words.addAll(new TextFile("UniqueWords.java", "\\W+"));
Iterator<String> it = words.iterator();
int totalNum = 0;
while (it.hasNext()) {
String word = it.next().toLowerCase(Locale.ROOT);
int num = 0;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (vowelWord.contains(c)) {
vowelExistMap.put(c, vowelExistMap.get(c) == null ? 1 : vowelExistMap.get(c) + 1);
num++;
}
}
System.out.print(word + " : " + num + " ");
totalNum += num;
}
System.out.println();
System.out.println("totalNum : " + totalNum);
System.out.println(vowelExistMap);
}
}
/* Output:
addall : 2 args : 1 case_insensitive_order : 9 class : 1 com : 1 demo : 2 elevensection : 6 example : 3 import : 2 java : 2 liran : 2 main : 2 new : 1 out : 2 package : 3 println : 1 project : 2 public : 2 set : 1 setoperations : 6 src : 0 static : 2 string : 1 system : 1 textfile : 3 treeset : 3 uniquewords : 5 users : 2 util : 2 void : 2 w : 0 words : 1
totalNum : 73
{a=14, e=25, u=6, i=16, o=12}
*///:~
posted @ 2022-08-24 18:47  loadL  阅读(17)  评论(0)    收藏  举报