java中判断数组中元素出现的次数

如题所示:有 20 个 0-9 之间的数字,并统计 0-9 这 10 个数字分别出现了多少次?
解答思路:声明两个数组,一个是需要判断元素出现次数的数组,另一个就是存放元素个数的数组,分别如下:
int num [] = {1,1,2,3,5,4,1,2,1,4,1,5,6,1,2,1,4,1,5,6};
int count [] = new int [10];
然后循环遍历该数组,通过switch简单读取,将其存放在count数组中。
代码如下:

//有 20 个 0-9 之间的数字,并统计 0-9 这 10 个数字分别出现了多少次?
    public static void test7(){
        int num [] = {1,1,2,3,5,4,1,2,1,4,1,5,6,1,2,1,4,1,5,6};
        int count [] = new int [10];
        for (int i = 0; i < num.length; i++) {
            switch (num[i]) {
            case 1:
                count[0]++;
                break;
            case 2:
                count[1]++;
                break;
            case 3:
                count[2]++;
                break;
            case 4:
                count[3]++;
                break;
                case 5:
                    count[4]++;
                    break;
                case 6:
                    count[5]++;
                    break;
                case 7:
                    count[6]++;
                    break;
                case 8:
                    count[7]++;
                    break;
                case 9:
                    count[8]++;
                    break;
                case 0:
                    count[9]++;
                    break;
            }
        }
        System.out.println("数字0出现的此时是:"+count[9]);
        System.out.println("数字1出现的此时是:"+count[0]);
        System.out.println("数字2出现的此时是:"+count[1]);
        System.out.println("数字3出现的此时是:"+count[2]);
        System.out.println("数字4出现的此时是:"+count[3]);
        System.out.println("数字5出现的此时是:"+count[4]);
        System.out.println("数字6出现的此时是:"+count[5]);
        System.out.println("数字7出现的此时是:"+count[6]);
        System.out.println("数字8出现的此时是:"+count[7]);
        System.out.println("数字9出现的此时是:"+count[8]);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穆雄雄

哎,貌似还没开张来着呢~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值