技术问询:如何实现Java数组中指定值的出现次数统计?
Got it, let's get your Java program working properly to check if a value exists in an array and count its occurrences. Here's the complete, polished version along with breakdowns of the fixes and additions:
Complete Working Code
import java.util.Scanner; public class ArrayValueCounter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] mas = new int[5]; // Step 1: Populate the array with user input for (int i = 0; i < mas.length; i++) { System.out.print("Input mas[" + i + "]: "); // Fix: Assign the input value to the array element mas[i] = sc.nextInt(); } // Step 2: Get the value the user wants to search for System.out.print("\nEnter the number you want to check: "); int target = sc.nextInt(); // Step 3: Run the count/check logic valueX(mas, target); sc.close(); } // Method to check existence and count occurrences public static void valueX(int[] arr, int targetValue) { int occurrenceCount = 0; // Traverse the array to count matches for (int num : arr) { if (num == targetValue) { occurrenceCount++; } } // Output results based on the count if (occurrenceCount > 0) { System.out.println("\nThe number " + targetValue + " exists in the array."); System.out.println("It appears " + occurrenceCount + " time(s)."); } else { System.out.println("\nThe number " + targetValue + " does NOT exist in the array."); } } }
Key Fixes & Explanations
- Fixed array population: Your original code read input but didn't store it in the
masarray. We addedmas[i] = sc.nextInt();to actually save each user input into the array. - Added target value input: We prompt the user to enter the number they want to search for, so we can pass it to the
valueXmethod. - Implemented the
valueXmethod: This method now takes the array and target value as parameters. It uses an enhanced for-loop to iterate through the array, counting how many times the target appears. - Removed the unnecessary loop: The
for (int i = 0; i < 10000; ...)block was irrelevant to the task, so we removed it to clean up the code. - Added clear result output: The method now tells the user explicitly if the value exists, plus how many times it shows up.
- Closed the Scanner: Properly closing the Scanner avoids resource leaks.
内容的提问来源于stack exchange,提问作者Oleg Khegay
相关产品推荐
相关产品推荐

