停车场迭代开发:TXT解析、字符串转整数及对象创建技术问询
Hey there! Let's break down how to tackle this multi-object parking lot project task step by step. I'll walk you through the class design, file parsing logic, and key implementation details to make this work smoothly.
解决方案:多对象停车场的文件解析与对象创建
1. First, Design the Class Structure
We'll use an abstract parent class for shared vehicle properties, then create subclasses for Auto and Bicycle to handle type-specific logic (even if you don't have unique methods yet, this structure scales well for future updates).
// Abstract parent class for all vehicles abstract class Vehicle { protected int speed; protected int passengerCapacity; protected String serialNumber; protected boolean isLocked; public Vehicle(int speed, int passengerCapacity, String serialNumber, boolean isLocked) { this.speed = speed; this.passengerCapacity = passengerCapacity; this.serialNumber = serialNumber; this.isLocked = isLocked; } // Optional: Add a toString method for easy debugging @Override public String toString() { return String.format("Type: %s | Speed: %d | Capacity: %d | Serial: %s | Locked: %b", this.getClass().getSimpleName(), speed, passengerCapacity, serialNumber, isLocked); } } // Car subclass class Auto extends Vehicle { public Auto(int speed, int passengerCapacity, String serialNumber, boolean isLocked) { super(speed, passengerCapacity, serialNumber, isLocked); } // Add car-specific methods here later (e.g., turnOnAC()) } // Bicycle subclass class Bicycle extends Vehicle { public Bicycle(int speed, int passengerCapacity, String serialNumber, boolean isLocked) { super(speed, passengerCapacity, serialNumber, isLocked); } // Add bicycle-specific methods here later (e.g., foldBike()) }
2. Read the File & Parse Each Line
Next, we'll read the .txt file line by line, split each line using % as the delimiter, convert string values to their proper types, and create the corresponding vehicle objects.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ParkingLotDataProcessor { public static void main(String[] args) { String filePath = "parking_vehicles.txt"; // Replace with your actual file path List<Vehicle> parkingVehicles = new ArrayList<>(); // Use try-with-resources to auto-close the file reader try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { // Skip empty lines to avoid errors if (line.trim().isEmpty()) continue; // Split the line into individual properties String[] vehicleProps = line.split("%"); // Validate the line format first if (vehicleProps.length != 5) { System.err.println("Skipping invalid line: " + line); continue; } try { // Parse each property to its correct type String vehicleType = vehicleProps[0]; int speed = Integer.parseInt(vehicleProps[1]); int capacity = Integer.parseInt(vehicleProps[2]); String serialNum = vehicleProps[3]; boolean isLocked = Boolean.parseBoolean(vehicleProps[4]); // Create the correct vehicle object based on type Vehicle newVehicle; switch (vehicleType) { case "Auto": newVehicle = new Auto(speed, capacity, serialNum, isLocked); break; case "Bicycle": newVehicle = new Bicycle(speed, capacity, serialNum, isLocked); break; default: System.err.println("Unknown vehicle type: " + vehicleType + " in line: " + line); continue; } parkingVehicles.add(newVehicle); System.out.println("Successfully created: " + newVehicle); } catch (NumberFormatException e) { // Catch errors when converting strings to integers System.err.println("Failed to parse numeric value in line: " + line + " | Error: " + e.getMessage()); } } System.out.println("\nTotal vehicles processed: " + parkingVehicles.size()); } catch (IOException e) { // Handle file reading errors (e.g., file not found) System.err.println("Error reading file: " + e.getMessage()); } } }
3. Key Implementation Notes
- String to Integer Conversion: Use
Integer.parseInt()for numeric fields, but always wrap this in a try-catch block to handle invalid number formats (like non-numeric characters in the speed/capacity fields). - Boolean Parsing:
Boolean.parseBoolean()will correctly convert "true" totrueand "false" tofalse(note: it's case-sensitive in Java—only lowercase "true" will returntrue). - File Safety: The
try-with-resourcessyntax ensures the file reader is automatically closed, preventing resource leaks. - Format Validation: Checking that each split line has exactly 5 parts avoids
ArrayIndexOutOfBoundsExceptionerrors.
4. Future Expansion Tips
- If you add more vehicle types later (e.g., Motorcycle), use a Factory Pattern to replace the switch statement for cleaner, more maintainable code.
- Extract the line-parsing logic into a separate method (like
parseVehicleLine(String line)) to keep your main code organized. - Store the parsed vehicle objects in a database or write them to a new file to integrate with future parking lot features (like check-in/check-out).
内容的提问来源于stack exchange,提问作者Steam261
相关产品推荐
相关产品推荐

