You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序求助:实现输入整数的对应频率统计数组功能

Hey there! Let's get your frequency array program up and running properly. I'll walk you through fixing and completing your code, step by step.

完整实现方案

First, let's finish your input code and add the logic to calculate the frequency of each element in the original array. Here's a complete, runnable version with explanations:

Full Working Code

import java.util.Scanner;

public class FrequencyArrayGenerator {
    public static void main(String[] args) {
        // Initialize the input array to hold 10 integers
        int[] arr = new int[10];
        Scanner s = new Scanner(System.in);

        // Collect 10 integers from the user
        for (int i = 0; i < arr.length; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            arr[i] = s.nextInt();
        }
        s.close(); // Always close the scanner when done using it

        // Create the Frequency array to store occurrence counts
        int[] frequency = new int[arr.length];
        
        // Calculate occurrence count for each element
        for (int i = 0; i < arr.length; i++) {
            int count = 0;
            // Loop through the entire array to count matches for current element
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] == arr[i]) {
                    count++;
                }
            }
            frequency[i] = count;
        }

        // Print out the results for verification
        System.out.println("\nOriginal input array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println("\nFrequency array:");
        for (int freq : frequency) {
            System.out.print(freq + " ");
        }
    }
}

Breakdown of the Code

  • Input Handling: I updated the prompt to be clearer (telling users which number they're entering) and fixed the incomplete nextInt() call. I also added s.close() to clean up the scanner resource.
  • Frequency Calculation:
    • We create a frequency array with the same length as the input array.
    • For each element in the input array, we loop through the entire array again to count how many times that element appears.
    • We assign that count to the corresponding position in the frequency array.
  • Result Output: We print both the original array and frequency array so you can easily check if the output matches your expected result.

Test Example

If you input 1 5 2 1 5 7 8 4 5 9, the program will output:

Original input array:
1 5 2 1 5 7 8 4 5 9 
Frequency array:
2 3 1 2 3 1 1 1 3 1 

Which is exactly the result you wanted!

Optional Optimization

For larger arrays, the double-loop approach can be slow. Here's a more efficient version using a HashMap to count occurrences in one pass, then build the frequency array:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class OptimizedFrequencyGenerator {
    public static void main(String[] args) {
        int[] arr = new int[10];
        Scanner s = new Scanner(System.in);

        for (int i = 0; i < arr.length; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            arr[i] = s.nextInt();
        }
        s.close();

        // Use HashMap to count each number's occurrences in one loop
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : arr) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        // Build the frequency array using the precomputed counts
        int[] frequency = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            frequency[i] = countMap.get(arr[i]);
        }

        // Print results
        System.out.println("\nOriginal input array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println("\nFrequency array:");
        for (int freq : frequency) {
            System.out.print(freq + " ");
        }
    }
}

This version runs in O(n) time instead of O(n²), making it much faster for big datasets.

内容的提问来源于stack exchange,提问作者DeadlyVenom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:55:30