如何将多个类合并为单个Java文件?附本人编写的代码示例
Fixing Your Single-File Rainfall Stats Class
Hey there! I see you're trying to keep all your rainfall statistics logic in a single Java file—great call for simplicity. Let's work through the issues in your current code and get it fully functional.
First, let's spot the problems in your existing code:
- The
totalRainfallvariable ingetTotalRainfall()isn't initialized, which will cause a compile error. getAverageRainfall()is trying to callgetTotalRainfall(...)with invalid parameters, but yourgetTotalRainfall()method doesn't take any arguments.- There's no way to initialize the
rainfallStatsarray, so you'd hit aNullPointerExceptionwhen trying to use it. - No main method to run the class directly (since you want a single executable file).
Here's the corrected, complete single-file version:
import javax.swing.JOptionPane; public class Raindrop { private double[] rainfallStats; // Constructor to initialize the rainfall data array public Raindrop(double[] rainfallData) { this.rainfallStats = rainfallData; } public double getTotalRainfall() { // Initialize total to 0.0 to start valid accumulation double totalRainfall = 0.0; for (int index = 0; index < rainfallStats.length; index++) { totalRainfall += rainfallStats[index]; } return totalRainfall; } public double getAverageRainfall() { // Guard against empty array to avoid division by zero if (rainfallStats == null || rainfallStats.length == 0) { return 0.0; } return getTotalRainfall() / rainfallStats.length; } // Main method to run the program directly from this single file public static void main(String[] args) { // Example: Get number of months from user String input = JOptionPane.showInputDialog("Enter number of months to track rainfall:"); int numMonths = Integer.parseInt(input); double[] rainfallData = new double[numMonths]; // Collect rainfall data for each month for (int i = 0; i < numMonths; i++) { String rainInput = JOptionPane.showInputDialog("Enter rainfall for month " + (i + 1) + ":"); rainfallData[i] = Double.parseDouble(rainInput); } // Create Raindrop instance and calculate stats Raindrop rainTracker = new Raindrop(rainfallData); double total = rainTracker.getTotalRainfall(); double average = rainTracker.getAverageRainfall(); // Display results JOptionPane.showMessageDialog(null, "Total Rainfall: " + total + " inches\n" + "Average Monthly Rainfall: " + average + " inches"); } }
Key improvements explained:
- Added a constructor to safely initialize the
rainfallStatsarray with user-provided data. - Initialized
totalRainfallto0.0ingetTotalRainfall()to ensure valid numeric accumulation. - Fixed
getAverageRainfall()to call the correct无参getTotalRainfall()method, plus added a check to avoid division by zero if the array is empty. - Added a main method so you can compile and run this single
.javafile directly, usingJOptionPaneto interact with the user for data input and result display.
内容的提问来源于stack exchange,提问作者Junior Planell LILCORE4
相关产品推荐
相关产品推荐

