java练习

有如下字符串,包含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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值