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

如何将多个类合并为单个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 totalRainfall variable in getTotalRainfall() isn't initialized, which will cause a compile error.
  • getAverageRainfall() is trying to call getTotalRainfall(...) with invalid parameters, but your getTotalRainfall() method doesn't take any arguments.
  • There's no way to initialize the rainfallStats array, so you'd hit a NullPointerException when 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 rainfallStats array with user-provided data.
  • Initialized totalRainfall to 0.0 in getTotalRainfall() 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 .java file directly, using JOptionPane to interact with the user for data input and result display.

内容的提问来源于stack exchange,提问作者Junior Planell LILCORE4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:10:37