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

如何从独立方法打印ArrayList?电厂数据分析程序打印功能实现求助

Fixing Your Power Plant Analyzer Program

Let's walk through the issues in your code and fix them so the PrintData method works correctly and your program runs as expected.

Key Issues in the Original Code

  • UploadData doesn't return the loaded data: Right now it creates an ArrayList<Entry> but returns null, so PrintData has no data to print.
  • Main loop logic is broken: Using separate while loops for each choice won't handle repeated menu selections correctly.
  • Missing parameter when calling PrintData: You're calling PrintData() without passing the ArrayList<Entry> it needs.
  • Case-sensitive variable mismatch: userChoice vs userchoice causes undefined variable errors.
  • Scanner newline leftover: After nextInt(), the newline character stays in the buffer, causing nextLine() to read an empty string when asking for the filename.

Fixed Full Code

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class PowerPlantAnalyzer {

    public static void main(String[] args) throws IOException {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Entry> dataList = null; // Store the loaded data here
        int userChoice;

        do {
            showMenu();
            userChoice = keyboard.nextInt();
            keyboard.nextLine(); // Clear the newline after nextInt()

            switch (userChoice) {
                case 1:
                    dataList = UploadData(keyboard); // Save the returned data
                    break;
                case 2:
                    if (dataList != null) {
                        PrintData(dataList); // Pass the loaded data to PrintData
                    } else {
                        System.out.println("Please upload data first!");
                    }
                    break;
                case 3:
                    System.out.println("Download Statistics feature coming soon!");
                    break;
                case 4:
                    System.out.println("Print Month feature coming soon!");
                    break;
                case 5:
                    System.out.println("Exiting program...");
                    break;
                default:
                    System.out.println("Invalid choice, please try again.");
            }
        } while (userChoice != 5); // Loop until user chooses exit

        keyboard.close();
    }

    public static void showMenu() {
        System.out.println("Welcome to the Power Plant Analyzer program. Please choose from the following options:\n" +
                " 1. Upload Data\n" +
                " 2. View Data \n" +
                " 3. Download Statistics \n" +
                " 4. Print Month \n" +
                " 5. Exit the program");
    }

    // Changed return type to ArrayList<Entry> and pass the existing Scanner
    public static ArrayList<Entry> UploadData(Scanner keyboard) throws IOException {
        System.out.println("What is the name of the file that contains the data?");
        String inputFileName = keyboard.nextLine();

        File f = new File(inputFileName);
        Scanner inputFile = new Scanner(f);

        ArrayList<Entry> monthList = new ArrayList<>();

        while (inputFile.hasNext()) {
            String m = inputFile.next();
            String d = inputFile.next();
            String y = inputFile.next();
            float p = inputFile.nextFloat();

            Entry entry = new Entry(m, d, y, p);
            monthList.add(entry);
        }

        inputFile.close();
        System.out.println("Data uploaded successfully!");
        return monthList; // Return the loaded list
    }

    // Now correctly accepts the ArrayList<Entry> parameter
    public static void PrintData(ArrayList<Entry> monthList) {
        System.out.println("\n--- Power Plant Data ---");
        for (Entry entry : monthList) {
            // Format output to match your example: Date: January 10, 2018 Output: 236.9
            System.out.printf("Date: %s %s, %s Output: %.1f%n", 
                entry.getMonth(), entry.getDay(), entry.getYear(), entry.getPowerOutput());
        }
        System.out.println("------------------------\n");
    }
}

class Entry {
    private String month;
    private String day;
    private String year;
    private float powerOutput;

    public Entry() {}

    public Entry(String m, String d, String y, float p) {
        month = m;
        day = d;
        year = y;
        powerOutput = p;
    }

    // Added getters to access private fields in PrintData
    public String getMonth() { return month; }
    public String getDay() { return day; }
    public String getYear() { return year; }
    public float getPowerOutput() { return powerOutput; }

    // Optional: Keep your original print method if needed
    public void print() {
        System.out.println("Month: " + month + " Day: " + day + " Year: " + year + " Power Output: " + powerOutput);
    }
}

What Changed & Why

  1. Stored loaded data in main: Added ArrayList<Entry> dataList to hold the data returned by UploadData.
  2. Fixed UploadData return type: Changed from String[] to ArrayList<Entry> and return the populated list instead of null. Also re-used the main Scanner to avoid newline issues.
  3. Redesigned main loop: Used a do-while loop with a switch statement for cleaner, more maintainable menu handling.
  4. Passed data to PrintData: Now calls PrintData(dataList) and checks if data exists first to avoid null errors.
  5. Added getters to Entry: Allowed PrintData to access private fields to format the output exactly as your example shows.
  6. Formatted output correctly: Used printf to match the requested output style (Date: January 10, 2018 Output: 236.9).

How to Test

  1. Run the program, choose option 1 and enter your data file name.
  2. Choose option 2—you'll see the data printed in the exact format you wanted.
  3. The menu will re-display after each action until you choose option 5 to exit.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:31:45