用java编成,实现从键盘输入一个字符串,统计出现频率最高的字符

如题所述

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a string :");
String line = in.nextLine();

Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
Integer integer = map.get(ch);
if (integer == null) {
map.put(ch, 1);
} else {
map.put(ch, integer + 1);
}
}

int length = line.length();
while (length > 0) {
for (Character c : map.keySet()) {
Integer count = map.get(c);
if (count == length) {
System.out.println("'" + c + "' : " + map.get(c));
}
}
length--;
}
}
}

输出:

Please enter a string :
hello world! hello java!
'l' : 5
' ' : 3
'o' : 3
'!' : 2
'a' : 2
'e' : 2
'h' : 2
'r' : 1
'd' : 1
'v' : 1
'w' : 1
'j' : 1

追问

谢谢

追答

哎呀呀,他回答的早是真的,不过他没有实现按出现频率大小顺序输出啊。

追问

你们都是大神

追答

原来是网友采纳,我错怪题主了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-09-19
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Main {

public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入.....");
char[] arr = in.readLine().toCharArray();
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < arr.length; i++){
Integer value = map.get(arr[i]);
if(value == null){
map.put(arr[i], 1);
}else{
map.put(arr[i], value+1);
}
}
System.out.println(map);
}
}

//输出的map我没有进行排序,你自己根据map的value排序一下就好了。

追问

谢谢

追答

不客气

本回答被网友采纳
第2个回答  2014-09-19
一样多都统计?
相似回答