第七章第三题(计算数字出现的次数)(Count the number of times a number appears)

第七章第三题(计算数字出现的次数)(Count the number of times a number appears)

  • **7.3(计算数字出现的次数)编写程序,读取1-100之间的整数,然后计算每个数出现的次数。假定输入0表示结束。下面是这个程序的一个运行示例:
    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
    **7.3(Count the number of times a number appears)Write a program, read the integer between 1-100, and then calculate the number of times each number appears. Suppose you enter 0 for the end. Here is a running example of this program:
    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
  • 参考代码:
package chapter07;

import java.util.Scanner;

public class Code_03 {
    public static void main(String[] args) {
        int[] numbers = new int[101];
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the integers between 1 and 100: ");
        String[] str = input.nextLine().split(" ");
        for (int i = 0;i < str.length;i++)
            numbers[Integer.parseInt(str[i])]++;
        for (int i = 1;i < numbers.length;i++){
            if (numbers[i] == 1)
                System.out.println(i + " occurs " + numbers[i] + " time ");
            else if (numbers[i] > 1)
                System.out.println(i + " occurs " + numbers[i] + " times ");
            else
                continue;
        }
    }
}

  • 结果显示:
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 

Process finished with exit code 0

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值