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

Java降水量统计程序功能优化咨询:如何正确显示极值对应月份及实现英尺英寸单位转换

Hey there! Let's tackle your two issues step by step, plus clean up some redundant code in your program to make it more maintainable.

Issue 1: Fixing Min/Max Month Display

The reason your program always shows January for the wettest/driest months is two-fold:

  1. Your original code only checks the first month (index 0) when calculating the lowest precipitation, instead of iterating through all 12 months.
  2. You never track the index of the month that has the highest/lowest value—you just hardcode EachMonth[0] in the final print statements.

How to Fix It:

  • Initialize two variables to track the indices of the min and max months (start with index 0 as a default):
    int lowestMonthIndex = 0;
    int highestMonthIndex = 0;
    
  • When looping through the precipitation array, update these indices whenever you find a new higher or lower value:
    for (int i = 0; i < 12; i++) {
        sum += a[i]; // Also fix your sum calculation here (no more duplicate a[4]!)
        if (a[i] > highest) {
            highest = a[i];
            highestMonthIndex = i; // Update the index for the new max
        }
        if (a[i] < lowest) {
            lowest = a[i];
            lowestMonthIndex = i; // Update the index for the new min
        }
    }
    
  • Finally, use these indices to get the correct month name in your print statements:
    System.out.println("The month with the least amount of precipitation was " + EachMonth[lowestMonthIndex] + " with " + lowest + " inches");
    System.out.println("The month with the most amount of precipitation was " + EachMonth[highestMonthIndex] + " with " + highest + " inches");
    

Issue 2: Converting Precipitation to Feet & Inches

Since 1 foot = 12 inches, we can split your total precipitation (assuming your input is in inches) into whole feet and remaining inches using basic arithmetic:

  • Calculate whole feet by dividing the total inches by 12 (use integer division to drop the decimal)
  • Calculate remaining inches using the modulus operator (%) to get the remainder after division

Example Code for Conversion:

// Convert total precipitation (in inches) to feet and inches
int totalFeet = (int) (totalPrecipitation / 12);
double remainingInches = totalPrecipitation % 12;

// Print the converted values
System.out.println("The total precipitation for the year was: " + totalFeet + " feet and " + remainingInches + " inches");

Improved Full Code

Here's your revised program with all fixes, plus reduced redundancy (no more 12 identical while loops!):

import java.util.Scanner;

public class Rain2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Double[] monthlyPrecip = new Double[12];
        int year = 0;
        String city = "";
        String[] monthNames = {"January", "February", "March", "April", "May", "June", 
                               "July", "August", "September", "October", "November", "December"};
        
        // Track min/max values AND their corresponding month indices
        double lowest = Double.MAX_VALUE; // Start with a very high number
        double highest = Double.MIN_VALUE; // Start with a very low number
        int lowestMonthIndex = 0;
        int highestMonthIndex = 0;
        
        double sum = 0;
        double average = 0;
        double totalPrecipitation;

        // Get city name
        System.out.println("Enter city name");
        city = scanner.next();

        // Get valid year
        do {
            System.out.println("Enter four digit number between 1900 and 2025");
            year = scanner.nextInt();
            if (year < 1900 || year > 2025) {
                System.out.println("Error: invalid input. Enter number between 1900 and 2025");
            }
        } while (year < 1900 || year > 2025);

        // Get monthly precipitation with validation (using a loop instead of 12 duplicate blocks)
        System.out.println("Enter the precipitation (in inches) for the following months (range: 0.0-50.0):");
        for (int i = 0; i < 12; i++) {
            while (true) {
                System.out.print(monthNames[i] + ": ");
                monthlyPrecip[i] = scanner.nextDouble();
                if (monthlyPrecip[i] >= 0.0 && monthlyPrecip[i] <= 50.0) {
                    break;
                } else {
                    System.out.println("Please enter value in the range [0.0-50.0]");
                }
            }
        }

        // Calculate sum, average, and track min/max months
        for (int i = 0; i < 12; i++) {
            sum += monthlyPrecip[i];
            if (monthlyPrecip[i] > highest) {
                highest = monthlyPrecip[i];
                highestMonthIndex = i;
            }
            if (monthlyPrecip[i] < lowest) {
                lowest = monthlyPrecip[i];
                lowestMonthIndex = i;
            }
        }
        totalPrecipitation = sum;
        average = sum / 12;

        // Print all monthly data
        System.out.println("\nPrecipitation Statistics for " + city + " in " + year + ":");
        for (int i = 0; i < 12; i++) {
            System.out.println(monthNames[i] + ": " + monthlyPrecip[i] + " inches");
        }

        // Print converted total precipitation
        int totalFeet = (int) (totalPrecipitation / 12);
        double remainingInches = totalPrecipitation % 12;
        System.out.println("\nThe total precipitation for the year was: " + totalFeet + " feet and " + remainingInches + " inches");
        
        // Print average, min, and max
        System.out.println("The average monthly precipitation for the year was: " + average + " inches");
        System.out.println("The month with the least amount of precipitation was " + monthNames[lowestMonthIndex] + " with " + lowest + " inches");
        System.out.println("The month with the most amount of precipitation was " + monthNames[highestMonthIndex] + " with " + highest + " inches");

        scanner.close();
    }
}

Key Improvements in the Revised Code:

  • Replaced 12 identical input loops with a single for loop (way less redundant!)
  • Fixed the sum calculation (no more duplicate a[4] or missing a[5])
  • Initialized lowest to Double.MAX_VALUE and highest to Double.MIN_VALUE to handle all valid input ranges
  • Added proper tracking of min/max month indices
  • Cleaned up variable names for readability (e.g., monthlyPrecip instead of a)
  • Added scanner.close() to prevent resource leaks

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:12:30