public class Test {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入0到50范围的数(输入-1结束)");
int num;
// 输入 -1 则输入结束
while ((num = scanner.nextInt()) != -1) {
if (num < 0 || num > 50) {
System.out.println(num + " 不在0到50范围,请重新输入");
continue;
}
Integer count = map.get(num);
map.put(num, count == null ? 1 : count + 1);
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
System.out.println("数字 " + entry.getKey() + " 出现了 " + entry.getValue() + " 次");
}
}
}
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/314e251f95cad1c87daa1a4c733e6709c93d514c?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)