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

来源:互联网 发布:网页写入js 编辑:程序博客网 时间:2024/05/22 01:49

如题所示:有 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]);    }