java作业:从键盘输入一个字符串,分别统计每个字符出现的次数。
package Exercise;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
publicclassTripOne {
publicstaticvoid main(String[] args) {
System.out.println("请输入一行字符串:");
Scannerscan=new Scanner(System.in);
Stringp=scan.next();
Mapmap=new HashMap<>();
for (inti = 0; i < p.length(); i++) {
intsum=0;
for (intj = 0; j < p.length(); j++) {
if(p.charAt(i)==p.charAt(j))
{
sum++;
}
}
map.put(p.charAt(i), sum);
}
List<Map.Entry<Character, Integer>>sf=new ArrayList<Map.Entry<Character, Integer>>(map.entrySet());
Collections.sort(sf, newComparator<Map.Entry<Character, Integer>>() {
publicint compare(Map.Entry<Character, Integer> o1,Map.Entry<Character, Integer> o2) {
//return (o2.getValue() - o1.getValue());
if(o1.getValue()>o2.getValue())
return -1;
elseif(o1.getValue()<o2.getValue())
return 1;
else
return 0;
}
});
for(inti = 0; i <sf.size(); i++) {
for (intj = 0; j < sf.get(i).getValue(); j++) {
System.out.print(sf.get(i).getKey());
}
}
}
}