如何将文件扫描得到的值赋值给Athlete对象的对应参数?
实现步骤
1. 先定义Athlete实体类
先创建包含对应属性的Athlete类,预留全参构造方法用于创建对象时直接赋值:
public class Athlete { // 三个属性对应存储姓名、A得分、B得分 private String name; private int scoreA; private int scoreB; // 全参构造方法 public Athlete(String name, int scoreA, int scoreB) { this.name = name; this.scoreA = scoreA; this.scoreB = scoreB; } // 按需添加getter、setter、toString方法即可 public String getName() { return name; } public int getScoreA() { return scoreA; } public int getScoreB() { return scoreB; } }
2. 修改文件扫描逻辑,拆分数据生成对象
调整你现有扫描代码的逻辑,读取每行后按分号拆分、处理字段格式,再创建Athlete对象即可:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ReadAthleteData { public static void main(String[] args) { // 用于存储所有读取到的运动员对象 List<Athlete> athleteList = new ArrayList<>(); File file = new File("input.txt"); try { Scanner scan = new Scanner(file); while (scan.hasNextLine()) { String line = scan.nextLine().trim(); // 跳过空行 if (line.isEmpty()) continue; // 按分号切割每行内容 String[] parts = line.split(";"); // 处理每个字段,去掉前后多余空格,得分转为int类型 String name = parts[0].trim(); int scoreA = Integer.parseInt(parts[1].trim()); int scoreB = Integer.parseInt(parts[2].trim()); // 调用构造方法创建对象,存入列表 Athlete athlete = new Athlete(name, scoreA, scoreB); athleteList.add(athlete); } scan.close(); // 可以遍历列表验证数据是否正确 for (Athlete a : athleteList) { System.out.printf("姓名:%s,A得分:%d,B得分:%d%n", a.getName(), a.getScoreA(), a.getScoreB()); } } catch (FileNotFoundException e) { System.out.println("未找到input.txt文件:" + e.getMessage()); } catch (NumberFormatException e) { System.out.println("得分格式解析失败:" + e.getMessage()); } } }
核心逻辑说明
- 调用
split(";")把每行文本按分号切割为字符串数组,三个元素分别对应姓名、A得分、B得分 - 每个元素调用
trim()去掉前后空格,避免解析数字时出现格式错误 - 用
Integer.parseInt()把字符串类型的得分转为int类型 - 所有创建完成的Athlete对象存储在List中,可直接用于后续业务逻辑处理
内容的提问来源于stack exchange,提问作者Mantas
相关产品推荐
相关产品推荐

