Chapter 7 Question 3 (Count the number of times a number appears)

Chapter 7 Question 3 (Count the number of times a number appears)

  • **7.3 (Count the number of occurrences of a number) Write a program to read an integer between 1-100, and then count the number of occurrences of each number. Assume that you enter 0 to indicate 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
    **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
  • Reference Code:
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;
        }
    }
}

  • The results show that:
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

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109264170