Java统计整数出现次数:如何让输入循环在7个整数后自动终止
Solution: Modify Input Loop to Stop After 7 Integers
Got it, let's tweak your code to automatically end after you enter exactly 7 integers instead of waiting for a 0 input. Here's the revised, cleaner version of your code:
package u07a1_numofoccurrinsevenints; import java.util.Scanner; public class U07A1_NumOfOccurrInSevenInts { public static void main(String[] args) { Scanner input = new Scanner(System.in); // We only need to store 7 numbers, so resize the array to match int number[] = new int[7]; // Use a practical size for count (adjust this if you expect larger input values) int count[] = new int[1000]; int temp = 0; System.out.print("Enter seven numbers: "); // Loop exactly 7 times to capture all required inputs for (int i = 0; i < 7; i++) { number[i] = input.nextInt(); } // Only iterate over the 7 numbers we actually stored (no wasted cycles) for (int i = 0; i < 7; i++) { temp = number[i]; count[temp]++; } for (int i = 0; i < count.length; i++) { if (count[i] > 0) { if (count[i] == 1) { System.out.printf("Number %d occurs %d time\n", i, count[i]); } else { System.out.printf("Number %d occurs %d times\n", i, count[i]); } } } input.close(); // Properly clean up the scanner resource } }
Key Changes Breakdown:
- Fixed Input Loop: Changed the input loop condition from
i < number.lengthtoi < 7— this guarantees we stop after collecting exactly 7 integers, no need for a terminating 0. - Optimized Array Sizes: Resized the
numberarray to 7 (since we only need to store 7 inputs) and shrank thecountarray to a more reasonable size (1000, adjust this if you need to handle larger integer values). - Efficient Statistics Calculation: Now we only loop through the 7 stored numbers instead of the entire giant original array, cutting down on unnecessary computation.
- Added Resource Cleanup: Added
input.close()to properly close the scanner, which is good Java coding practice.
Sample Run Output:
run: Enter seven numbers: 12 23 44 22 23 22 55 Number 12 occurs 1 time Number 22 occurs 2 times Number 23 occurs 2 times Number 44 occurs 1 time Number 55 occurs 1 time BUILD SUCCESSFUL (total time: 10 seconds)
内容的提问来源于stack exchange,提问作者Quenten Guiles
相关产品推荐
相关产品推荐

