数组:根据输入情况判断数字出现次数

Java基础刚学到数组,这道题花了比较长的时间去做,总感觉会有更简便的方法去完成。

再学习一段时间后回来完善

题目:

创建10个长度的整数数组arr,从控制台依次录入10个整数并装进数组中,
要求:录入的数字只能是1 ~ 5,如果录入的数字不符合范围,则提示用户“录入有误,请重试”,
录入完毕后,求:数组中共包含几种数字,以及每种数字出现的次数,例如:
数组中出现的数字共有4种,分别是1, 2, 4, 5
数字1出现的次数为:3次
数字2出现的次数为:2次
数字4出现的次数为:1次
数字5出现的次数为:4次

int [] arr = new int[10];
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        int one = 0;
        int two = 0;
        int thr = 0;
        int four = 0;
        int five = 0;
        int count = 0;
        for (int i = 0; i < 10; i++) {
            System.out.println("请输入1~5中任意一个数字");
            int a = sc.nextInt();
            if (a >= 0 && a <= 5){
                sum++;
                arr[i] = a;
                switch (a){
                    case 1:
                        one++;
                        break;
                    case 2:
                        two++;
                        break;
                    case 3:
                        thr++;
                        break;
                    case 4:
                        four++;
                        break;
                    case 5:
                        five++;
                        break;
                }

            }if(a < 1 || a > 5){
                System.out.println("录入有误,请重试");
                i--;
            }
        }
        if (one!=0){count+=1;}
        if (two!=0){count+=1;}
        if (thr!=0){count+=1;}
        if (four!=0){count+=1;}
        if (five!=0){count+=1;}


        System.out.println(sum);
        System.out.println(Arrays.toString(arr));
        System.out.print("数组中出现的数字共有" + count + "种,分别是:");
        if (one!=0){
            System.out.print("1 ");
        }
        if (two!=0){
            System.out.print("2 ");
        }
        if (thr!=0){
            System.out.print("3 ");
        }
        if (four!=0){
            System.out.print("4 ");
        }
        if (five!=0){
            System.out.println("5 ");
        }

        System.out.println("数字1出现的次数为:" + one + "次");
        System.out.println("数字2出现的次数为:" + two + "次");
        System.out.println("数字3出现的次数为:" + thr + "次");
        System.out.println("数字4出现的次数为:" + four + "次");
        System.out.println("数字5出现的次数为:" + five + "次");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值