Java读取文本文件:差异化处理首行与动态计算优化
优化方案:拆分逻辑+动态循环处理可变天数
Alright, let's fix this problem step by step. The core issue here is separating the initial stats setup from the dynamic race day calculations, so you don't have to copy-paste code for every single race event. Here's how to do it properly:
1. Core Optimization Ideas
- Split first-line handling: Read the first line separately to extract the car's initial
healthandpower, then collect any race days included in that line. - Dynamically gather all race days: Read all subsequent lines and add every valid number to a list of race intervals.
- Unified loop calculation: Iterate through the list of race days, reusing the same calculation logic to update the car's stats each time—no hardcoding required.
2. Optimized Complete Code Example
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CarRaceSimulator { private BufferedReader reader; private int currentHealth; private int currentPower; public CarRaceSimulator() { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the name of the text file you wish to import. Choose either inputs or lotsainputs. Nothing else"); String filename = keyboard.nextLine(); File file = new File(filename); System.out.println("You have loaded file: " + filename); try { reader = new BufferedReader(new FileReader(file)); processFile(); } catch (FileNotFoundException e) { System.err.println("File not found: " + filename); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); keyboard.close(); } catch (Exception e) { e.printStackTrace(); } } } private void processFile() throws Exception { // Handle first line: extract initial stats and any race days in the line String firstLine = reader.readLine(); if (firstLine == null) { System.err.println("Empty file!"); return; } String[] firstLineParts = firstLine.trim().split("\\s+"); if (firstLineParts.length < 2) { System.err.println("Invalid first line: must contain at least health and power"); return; } // Parse initial car stats try { currentHealth = Integer.parseInt(firstLineParts[0]); currentPower = Integer.parseInt(firstLineParts[1]); } catch (NumberFormatException e) { System.err.println("Invalid number format in first line"); e.printStackTrace(); return; } System.out.println("Initial car stats - Health: " + currentHealth + ", Power: " + currentPower); // Collect all race days: start with remaining numbers in first line List<Integer> raceDays = new ArrayList<>(); for (int i = 2; i < firstLineParts.length; i++) { try { raceDays.add(Integer.parseInt(firstLineParts[i])); } catch (NumberFormatException e) { System.err.println("Ignoring invalid number in first line: " + firstLineParts[i]); } } // Add race days from all subsequent lines String line; while ((line = reader.readLine()) != null) { String[] lineParts = line.trim().split("\\s+"); for (String part : lineParts) { try { raceDays.add(Integer.parseInt(part)); } catch (NumberFormatException e) { System.err.println("Ignoring invalid number in line: " + part); } } } // Process each race day dynamically with a loop System.out.println("\nProcessing " + raceDays.size() + " race events..."); for (int days : raceDays) { updateCarStats(days); System.out.println("After " + days + " days - Health: " + currentHealth + ", Power: " + currentPower); } } // Reusable calculation logic for car stat updates private void updateCarStats(int days) { // Replace this with your actual损耗 calculation logic // Example: Health decreases by 1 per day, Power decreases by 2 per day currentHealth -= days * 1; currentPower -= days * 2; // Optional: Prevent stats from dropping below 0 currentHealth = Math.max(currentHealth, 0); currentPower = Math.max(currentPower, 0); } public static void main(String[] args) { new CarRaceSimulator(); } }
3. Key Improvements Explained
- Separation of concerns: Initial stats are set once from the first line, and all race days are handled in a single loop.
- Dynamic scalability: The code works with any number of race days—no need to copy-paste calculation code for each event.
- Better error handling: Invalid numbers are caught and ignored instead of crashing the program.
- Cleaner structure: Logic is split into dedicated methods (
processFile,updateCarStats) for readability and maintainability. - Resource management: Streams and scanners are properly closed in a
finallyblock to avoid resource leaks.
4. Works With Your File Examples
For your first example file:
200 345 36
The program will initialize health=200, power=345, then process the 36-day interval and output the updated stats.
For your second example file:
200 345 36 45 36 21
It will process all four race intervals (36, 45, 36, 21) in sequence, updating the car's stats each time.
This setup also works if your file has the initial stats on the first line and each race day on its own subsequent line—no changes needed.
内容的提问来源于stack exchange,提问作者Smurf1
相关产品推荐
相关产品推荐

