Java数组查找最小值异常:初始化导致结果恒为0的修复方案
Hey there! I see exactly what's going wrong here—let's break it down and fix it quickly.
The Root Problem
You're initializing min and max to temperature[0] right after creating the array. But when you create a new int[] in Java, all elements default to 0 before you input any values. That means even if you later enter temperatures higher than 0, your min starts at 0 and never gets updated if all inputs are warmer than that.
Two Simple Fixes
Fix 1: Input All Values First, Then Initialize Min/Max
First, fill the array with user input completely, then set min and max to the first actual temperature value (not the default 0). Here's the updated code:
int[] temperature = new int[12]; Scanner kb = new Scanner(System.in); // Step 1: Fill the array with user input first for (int i = 0; i < temperature.length; i++) { System.out.print("Enter temperature for month " + (i + 1) + ": "); temperature[i] = kb.nextInt(); } // Now initialize min/max with the first valid temperature int min = temperature[0]; int max = temperature[0]; // Step 2: Iterate to find min and max for (int i = 1; i < temperature.length; i++) { if (temperature[i] < min) { min = temperature[i]; } if (temperature[i] > max) { max = temperature[i]; } } // Output results System.out.println("Minimum temperature: " + min); System.out.println("Maximum temperature: " + max); kb.close();
Fix 2: Update Min/Max As You Input Values (More Efficient)
You don't even need to wait until the array is full—you can update min and max immediately after each input. To avoid using the default 0, initialize min to the highest possible integer value and max to the lowest possible:
Scanner kb = new Scanner(System.in); int min = Integer.MAX_VALUE; // Starts at the largest int, so first input will replace it int max = Integer.MIN_VALUE; // Starts at the smallest int, so first input will replace it int[] temperature = new int[12]; for (int i = 0; i < temperature.length; i++) { System.out.print("Enter temperature for month " + (i + 1) + ": "); temperature[i] = kb.nextInt(); // Update min and max right after input if (temperature[i] < min) { min = temperature[i]; } if (temperature[i] > max) { max = temperature[i]; } } System.out.println("Minimum temperature: " + min); System.out.println("Maximum temperature: " + max); kb.close();
Why These Work
- Fix 1 ensures
minandmaxstart with a real user-provided value instead of the default 0. - Fix 2 uses extreme initial values that guarantee the first input will overwrite them, so you never have to worry about default values messing up your results.
内容的提问来源于stack exchange,提问作者Chaite

