有如下字符串,包含3条关于水果数量的信息
“5 西瓜 苹果 蓝莓 苹果 苹果 3 桃 橙子 桃 0”
数字代表该数字后面出现的一组信息的水果数量,直到出现0为止,代表信息结束。
请输出每组信息中出现次数最多的水果。
(假设每组信息都保证有数量最多的1种水果)
解答:
import java.util.HashMap;
import java.util.Map;
public class demo3 {
public static void main(String[] args) {
String fruit = "5 西瓜 苹果 蓝莓 苹果 苹果 3 桃 橙子 桃 0";
final String[] split = fruit.split("\\s+");
int currentPosition = 0;
while (currentPosition < split.length) {
HashMap<String, Integer> map = new HashMap<>();
final int parseInt = Integer.parseInt(split[currentPosition]);
if (parseInt == 0) {
break;
}
for (int i = currentPosition + 1; i <= currentPosition + parseInt; i++) {
if (map.containsKey(split[i])) {
map.put(split[i], map.get(split[i]) + 1);
} else {
map.put(split[i], 1);
}
}
String maxKey = null;
int maxValue = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > maxValue) {
maxKey = entry.getKey();
maxValue = entry.getValue();
}
}
System.out.println("该组信息中出现次数最多的水果是" + maxKey + "次数是" + maxValue);
currentPosition += parseInt + 1;
}
}
}