Java新手求助:数组元素关联Sports类属性赋值问题
解决Sports类内部实现属性赋值的问题
Hey there! Let's break this down step by step—since you're new to Java, I'll keep things clear and actionable. The goal is to move all the file reading and attribute assignment logic into the Sports class itself, rather than handling it in Main. Here's how to do it:
Step 1: Design the Sports Class with Internal Logic
First, we'll build the Sports class to handle loading sport data from the file, caching it, and populating each object's attributes. We'll use a static cache so we only read the file once, which is efficient.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Sports { // Private attributes for the sport private int id; private String name; private int caloriesPerHour; // Constructor: takes the known sport ID (from your array) public Sports(int id) { this.id = id; } // Static cache to store all sport data from the file (ID -> name + calories) private static Map<Integer, SportInfo> sportDataCache = new HashMap<>(); // Static inner class to hold temporary sport data from the file private static class SportInfo { String name; int calories; SportInfo(String name, int calories) { this.name = name; this.calories = calories; } } // Static method to load data from the file into the cache public static void loadSportData(String filePath) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; // Skip the header line if your file has one (like "ID Name Calories") reader.readLine(); while ((line = reader.readLine()) != null) { // Split the line by tab character (\t) String[] parts = line.split("\\t"); // Validate line format if (parts.length != 3) { System.err.println("Skipping invalid line: " + line); continue; } try { int sportId = Integer.parseInt(parts[0]); String sportName = parts[1]; int calories = Integer.parseInt(parts[2]); // Add to cache sportDataCache.put(sportId, new SportInfo(sportName, calories)); } catch (NumberFormatException e) { System.err.println("Error parsing numbers in line: " + line); } } } } // Instance method to populate name and calories using the cache public void fillAttributes() { SportInfo info = sportDataCache.get(this.id); if (info != null) { this.name = info.name; this.caloriesPerHour = info.calories; } else { System.err.println("No data found for sport ID: " + this.id); } } // Getters to access the attributes public int getId() { return id; } public String getName() { return name; } public int getCaloriesPerHour() { return caloriesPerHour; } }
Step 2: Use the Sports Class in Main
In your Main class, you just need to load the data once, then create Sports objects for each ID in your array and trigger the attribute population.
import java.io.IOException; public class Main { public static void main(String[] args) { // Your array of sport IDs int[] sportIds = {1, 3, 5}; // First, load the sport data into the Sports class cache try { Sports.loadSportData("sports_info.txt"); } catch (IOException e) { System.err.println("Failed to load sport data: " + e.getMessage()); return; } // Create Sports objects for each ID and fill their attributes Sports[] sportsArray = new Sports[sportIds.length]; for (int i = 0; i < sportIds.length; i++) { sportsArray[i] = new Sports(sportIds[i]); // Call the method inside Sports to populate attributes sportsArray[i].fillAttributes(); } // Test the results for (Sports sport : sportsArray) { System.out.printf("Sport ID: %d | Name: %s | Calories/Hour: %d%n", sport.getId(), sport.getName(), sport.getCaloriesPerHour()); } } }
Key Notes for You
- File Format: Make sure your file uses tabs (
\t) to separate values. Example line:1 Running 600 - Error Handling: We added basic error handling for invalid lines or number parsing—this helps your program not crash unexpectedly.
- Static Cache: The cache is static, so we only read the file once. This is much more efficient than reading it for every
Sportsobject. - Encapsulation: All the logic for handling sport data is inside the
Sportsclass, which keeps your code organized and follows good OOP practices.
内容的提问来源于stack exchange,提问作者gokhan_ozeloglu
相关产品推荐
相关产品推荐

