前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第七章第三题(计算数字的出现次数)(Count occurrence of numbers) - 编程练习题答案

第七章第三题(计算数字的出现次数)(Count occurrence of numbers) - 编程练习题答案

作者头像
无刺鱼
发布2022-03-29 13:15:04
3040
发布2022-03-29 13:15:04
举报
文章被收录于专栏:许唯宇

编写程序,读取在1到100 之间的整数,然后计算每个数出现的次数。假定输入是以0 结束的。

下面是这个程序的一个运行示例:

Write a program that reads the integers between 1and 100 and counts the occurrences of each. Assume the input ends with 0.Note that if a number occurs more than one time, the plural word “times” is used

in the output.

代码语言:javascript
复制
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time

下面是参考答案代码:

代码语言:javascript
复制
// https://cn.fankuiba.com
import java.util.Scanner;

public class Ans7_3_page236 {
    public static void main(String[] args) {
        int[] number = new int [101];
        Scanner input = new Scanner(System.in);
        int num;
        System.out.print("Enter the integers between 1 and 100: ");
        do {
            num = input.nextInt();
            number[num] = number[num] + 1;
        }
        while (num != 0);
        for (int i = 1; i < number.length; i++) {
            if (number[i] == 1) {
                System.out.println(i + " occurs " + number[i] + " time");
            }else if (number[i] > 1)
                System.out.println(i + " occurs " + number[i] + " times");
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档