Count Target Number


Submit solution

Points: 10 (partial)
Time limit: 1.0s
Memory limit: 64M

Authors:
Problem type
Allowed languages
Java 19, Java 8

這個程式允許使用者輸入一個整數n,和後續的n個整數,最後再輸入一個目標整數。

輸入完成之後,程式會計算n個整數中出現了幾次目標整數,並且印出結果。

這個程式目前仍缺少countTargetNumber函數的實作,請完成它,並且上傳完整的程式。 除了countTargetNumber函數之外,請勿修改其他已經寫好的部分,違反此規則者,無論自動評測結果為何,在考試中均不計分。但允許輕微的排版差異。

程式完成之後,可用以下測試資料做初步的測試,但仍請自行設計完整的測試資料

輸入 #1:

5 1 4 3 4 5 3

輸出 #1:

1 (因為1,4,3,4,5這5個數字裡面出現了1次3)

輸入 #2:

5 1 4 3 4 5 4

輸出 #2:

2 (因為1,4,3,4,5這5個數字裡面出現了2次4)

輸入 #3:

5 1 4 3 4 5 7

輸出 #3:

0 (因為1,4,3,4,5這5個數字裡面出現了0次7)

import java.util.Scanner;

public class CountTargetNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 讀取數字的數量,這是使用者輸入的第一個數字,並創建一個大小為 n 的整數陣列
        int n = scanner.nextInt();
        int[] numbers = new int[n];

        // 接著讀取 n 個數字,並將它們存儲在 numbers 陣列中
        for (int i = 0; i < n; i++) {
            numbers[i] = scanner.nextInt();
        }

        // 讀取目標數字 
        int target = scanner.nextInt();

        // 計算 numbers 陣列中目標數字的出現次數
        // 函數的返回值是一個整數,參數是一個整數陣列和一個整數
        int result = countTargetNumber(numbers, target);

        System.out.println(result);

        scanner.close();
    }

    // 這個函數計算 numbers 陣列中目標數字的出現次數
    // 參數是一個整數陣列和一個目標整數,返回值是一個整數,表示目標數字的出現次數
    public static ... countTargetNumber(...) {
        ...
    }
}

Comments

There are no comments at the moment.