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 + "次"); } }