如何从独立方法打印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
UploadDatadoesn't return the loaded data: Right now it creates anArrayList<Entry>but returnsnull, soPrintDatahas no data to print.- Main loop logic is broken: Using separate
whileloops for each choice won't handle repeated menu selections correctly. - Missing parameter when calling
PrintData: You're callingPrintData()without passing theArrayList<Entry>it needs. - Case-sensitive variable mismatch:
userChoicevsuserchoicecauses undefined variable errors. - Scanner newline leftover: After
nextInt(), the newline character stays in the buffer, causingnextLine()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
- Stored loaded data in main: Added
ArrayList<Entry> dataListto hold the data returned byUploadData. - Fixed
UploadDatareturn type: Changed fromString[]toArrayList<Entry>and return the populated list instead ofnull. Also re-used the mainScannerto avoid newline issues. - Redesigned main loop: Used a
do-whileloop with aswitchstatement for cleaner, more maintainable menu handling. - Passed data to
PrintData: Now callsPrintData(dataList)and checks if data exists first to avoid null errors. - Added getters to
Entry: AllowedPrintDatato access private fields to format the output exactly as your example shows. - Formatted output correctly: Used
printfto match the requested output style (Date: January 10, 2018 Output: 236.9).
How to Test
- Run the program, choose option 1 and enter your data file name.
- Choose option 2—you'll see the data printed in the exact format you wanted.
- The menu will re-display after each action until you choose option 5 to exit.
内容的提问来源于stack exchange,提问作者Nitro
相关产品推荐
相关产品推荐

