You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中从外部文件提取数据创建flyweight和featherweight分数数组

解决方案

你可以用ArrayList动态收集两个类别的分数,之后如果需要数组再做转换,这种方式比固定长度数组更灵活(无需提前知道每个类别的数据量)。

完整代码示例

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner readFile = new Scanner(Main.class.getResourceAsStream("boxingcompetition.txt"));
        int competition = Integer.parseInt(readFile.nextLine());
        int totalCompetition = competition * 2;
        
        // 初始化两个列表,分别存两个类别的分数
        ArrayList<Integer> flyweightScores = new ArrayList<>();
        ArrayList<Integer> featherweightScores = new ArrayList<>();
        
        String line;
        String[] lineSplit;
        String name;
        int score;
        String categories;
        
        for (int i = 1; i <= totalCompetition; i++) {
            line = readFile.nextLine();
            lineSplit = line.split(",");
            name = lineSplit[0];
            score = Integer.parseInt(lineSplit[1]);
            categories = lineSplit[2];
            
            // 判断类别,把分数加入对应列表
            if (categories.equals("flyweight")) {
                flyweightScores.add(score);
            } else if (categories.equals("featherweight")) {
                featherweightScores.add(score);
            }
        }
        readFile.close(); // 记得关闭输入流
        
        // 可选:把列表转成int数组
        int[] flyweightArray = flyweightScores.stream().mapToInt(Integer::intValue).toArray();
        int[] featherweightArray = featherweightScores.stream().mapToInt(Integer::intValue).toArray();
        
        // 测试输出(可选)
        System.out.println("Flyweight分数数组:");
        for (int s : flyweightArray) {
            System.out.print(s + " ");
        }
        System.out.println("\nFeatherweight分数数组:");
        for (int s : featherweightArray) {
            System.out.print(s + " ");
        }
    }
}

关键说明

  • 用ArrayList可以自动扩容,不用提前计算每个类别的数据数量,避免数组长度不足的问题
  • 循环里通过categories判断,将对应分数添加到指定列表
  • 如果需要int数组,用Stream API可以快速转换,也可以手动循环实现
  • 操作完文件后一定要关闭Scanner,避免资源泄漏

内容的提问来源于stack exchange,提问作者aurellia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 14:59:58