如何使用分隔符读取文本文件为对象数组?含师生数据处理需求
Solution to Reading Teacher and Student Data from File
I'll walk you through a Java-based implementation since the Student constructor follows Java syntax. Here's how to tackle this task:
Core Steps
- Open and read the target text file line by line
- Extract the first three lines to populate your teacher-related string variables
- Parse each subsequent line into the required parameters for
Studentobjects and collect them into an array
Full Code Example
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class DataReader { // Define the Student class as per your constructor signature static class Student { private String name; private int ID; private int grade1; private int grade2; private int grade3; private int grade5; private int grade6; private int grade7; private int grade8; private int grade9; private int grade10; public Student(String name, int ID, int grade1, int grade2, int grade3, int grade5, int grade6, int grade7, int grade8, int grade9, int grade10) { this.name = name; this.ID = ID; this.grade1 = grade1; this.grade2 = grade2; this.grade3 = grade3; this.grade5 = grade5; this.grade6 = grade6; this.grade7 = grade7; this.grade8 = grade8; this.grade9 = grade9; this.grade10 = grade10; } // Optional: Add toString() for debugging @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", ID=" + ID + ", grades=" + grade1 + "," + grade2 + "," + grade3 + "," + grade5 + "," + grade6 + "," + grade7 + "," + grade8 + "," + grade9 + "," + grade10 + '}'; } } public static void main(String[] args) { String teacherName = ""; String subject = ""; String teachingHours = ""; List<Student> studentList = new ArrayList<>(); String filePath = "your_data_file.txt"; // Replace with your actual file path try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { // Read first three lines for teacher info teacherName = br.readLine().trim(); subject = br.readLine().trim(); teachingHours = br.readLine().trim(); String line; // Read remaining lines for student data while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; // Skip empty lines // Split line into parts (assuming data is separated by commas or spaces; adjust delimiter as needed) String[] parts = line.split("\\s+|,"); // Handles spaces or commas as separators if (parts.length != 11) { System.err.println("Invalid student data line: " + line); continue; // Skip invalid lines } try { String studentName = parts[0]; int id = Integer.parseInt(parts[1]); int g1 = Integer.parseInt(parts[2]); int g2 = Integer.parseInt(parts[3]); int g3 = Integer.parseInt(parts[4]); int g5 = Integer.parseInt(parts[5]); int g6 = Integer.parseInt(parts[6]); int g7 = Integer.parseInt(parts[7]); int g8 = Integer.parseInt(parts[8]); int g9 = Integer.parseInt(parts[9]); int g10 = Integer.parseInt(parts[10]); Student student = new Student(studentName, id, g1, g2, g3, g5, g6, g7, g8, g9, g10); studentList.add(student); } catch (NumberFormatException e) { System.err.println("Error parsing numbers in line: " + line); e.printStackTrace(); } } // Convert list to array if needed Student[] studentArray = studentList.toArray(new Student[0]); // Optional: Print results to verify System.out.println("Teacher Name: " + teacherName); System.out.println("Subject: " + subject); System.out.println("Teaching Hours: " + teachingHours); System.out.println("Students:"); for (Student s : studentArray) { System.out.println(s); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } } }
Key Notes
- File Path: Replace
your_data_file.txtwith the actual path to your text file. - Data Delimiter: The code uses
\\s+|,to split lines, which works for spaces or commas. Adjust this regex if your data uses a different separator (like tabs:\\t). - Error Handling: The code includes checks for invalid line lengths and number format errors to avoid crashes from malformed data.
- Resource Management: We use a try-with-resources block for
BufferedReaderto ensure the file is closed automatically. - List to Array: We convert the
ArrayList<Student>to aStudent[]array usingtoArray(new Student[0])as requested.
Tip: If your student data lines have names with spaces (e.g., "John Doe"), you'll need a more sophisticated parsing method (like CSV parsing with a library) instead of simple splitting, since spaces in names would break the current split logic.
内容的提问来源于stack exchange,提问作者Alex G
相关产品推荐
相关产品推荐

