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 addeds.close()to clean up the scanner resource. - Frequency Calculation:
- We create a
frequencyarray 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
frequencyarray.
- We create a
- 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

