编写一个应用程序,利用数组或者集合, 求出"HELLO",“JAVA”,“PROGRAM”,“EXCEPTION”四个字符串的平均长度以及字符出现重复次数最多的字符串。

public class Number {
	public static void main(String[] args) {
		String[] arr = { "HELLO", "JAVA", "PROGRAM", "EXCEPTION" };
		double sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i].toCharArray().length;
		}
		double avg = sum / arr.length;
		System.out.println("四个字符串的平均长度为:" + avg);
		ArrayList<Map<Character, Integer>> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++) {
			Map<Character, Integer> map = new HashMap<Character, Integer>();
			char[] str = arr[i].toCharArray();
			for (int j = 0; j < str.length; j++) {
				if(map.get(str[j])!=null) {
					map.put(str[j], map.get(str[i])+1);
				}else {
					map.put(str[j], 1);
				}
			}
			list.add(map);	
		}
		int max = -1;
		for (int i = 0; i < list.size(); i++) {
			for (Map.Entry<Character, Integer> entry : list.get(i).entrySet()) {
				if(max < entry.getValue()) {
					max = entry.getValue();
				}
			}
		}
		for (int i = 0; i < list.size(); i++) {
			for (Map.Entry<Character, Integer> entry : list.get(i).entrySet()) {
				if(max == entry.getValue()) {
					System.out.println(arr[i]);
					break;
				}
			}
		}
	}
}
posted @ 2020-12-13 16:12  MikiKawai  阅读(233)  评论(0编辑  收藏  举报