1、读取个数不定的整数,查找出现频率最高的数字。输入为0时,结束输入。出现频率最高的数字可能是一个或者多个,将这些数字以及对应的次数输出。
2、读入一串文本,统计单词出现的次数,单词由空格和标点分隔。分别按单词字母顺序和次数顺序从小到大输出单词以及出现的次数。
运行结果截图
第一题:
第二题:
源代码:
第一题
package com.serein;
import java.util.*;
public class SomeStringOpeter2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一些整数:");
Map<Integer,Integer> maps = new HashMap<>();
int text = sc.nextInt();
while (text != 0){
if (maps.get(text) == null){
maps.put(text,1);
}else {
maps.put(text,maps.get(text) + 1);
}
text = sc.nextInt();
}
Collection<Integer> c = maps.values();
Object[] obj = c.toArray();
Arrays.sort(obj);
for (Map.Entry<Integer, Integer> entry : maps.entrySet()) {
if (obj[obj.length - 1] == entry.getValue()){
System.out.println("出现频率最高的数字:" + entry.getKey() + ",出现" + obj[maps.size() - 1] + "次");
}
}
}
}
第二题
package com.serein;
import java.util.*;
public class SomeStringOpeter3 {
public static void main(String[] args) {
String text = "Life is too short to spend time with people who suck the happiness out of you. " +
"If someone wants you in their life, they’ll make room for you. You shouldn’t have to fight for a spot. ";
System.out.println("按字母顺序输出:");
System.out.println(order(text));
System.out.println("按单词出现次数输出:");
System.out.println(frequency(text));
}
private static String frequency(String text) {
StringBuilder sb = new StringBuilder();
Map<String,Integer> map = new HashMap<>();
String[] sList = text.split(" |,|\\.");
for (int i = 0; i < sList.length; i++) {
if (!map.containsKey(sList[i])) {
map.put(sList[i], 1);
}else {
map.put(sList[i],map.get(sList[i]) + 1);
}
}
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list,(Comparator.comparing(Map.Entry::getValue)));
Iterator<Map.Entry<String,Integer>> iterator = list.iterator();
while (iterator.hasNext()){
Map.Entry<String,Integer> entry = iterator.next();
String key = entry.getKey();
int value = entry.getValue();
System.out.println(key + "==>" + value);
}
return sb.toString();
}
private static String order(String text) {
StringBuilder sb = new StringBuilder();
Map<String,Integer> map = new TreeMap<>();
String[] sList = text.split(" |,|\\.");
for (int i = 0; i < sList.length; i++) {
if (!map.containsKey(sList[i])) {
map.put(sList[i], 1);
}else {
map.put(sList[i],map.get(sList[i]) + 1);
}
}
Set<String> keys = map.keySet();
for (String key : keys) {
int value = map.get(key);
System.out.println(key + "-->" + value);
}
return sb.toString();
}
}
今天的分享就到这里,如果觉得有帮助,欢迎评论点赞转发哦!你们的支持是我更新的最大动力!