Linear search in Java The number of occurrences

Implement a method to count the number of occurrences of a value in an array of int's.

Sample Input 1:

19 14 17 15 17
17
Sample Output 1:

2
Sample Input 2:

101 120 103 240
150
Sample Output 2:

0

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static int count(int[] numbers, int value) {
        int count = 0;
        for (int temp : numbers) {
            if (temp == value) {
                ++count;
            }
        }
        return count;
    }

    /* Do not change code below */
    @SuppressWarnings("Duplicates")
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int[] numbers;
        final int k;
        if (scanner.hasNextInt()) {
            numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
                    .mapToInt(Integer::parseInt)
                    .toArray();
            k = Integer.parseInt(scanner.nextLine());
        } else {
            numbers = new int[0];
            k = 10;
        }
        System.out.println(count(numbers, k));
    }
}
posted @ 2020-08-14 07:29  longlong6296  阅读(94)  评论(0)    收藏  举报