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

Java中如何检测数据文件的双换行以统计精灵卡路里总量?

如何正确检测数据文件中的双换行(Java实现)

你的代码报错的核心原因是Scanner默认的分隔规则会忽略所有空白字符(包括单个/多个换行、空格、制表符等),所以input.next()永远无法获取到"\n\n"。而且每次调用input.next()会跳过当前数字后的空白,直接读取下一个数字token,这会导致你跳过部分数值,甚至触发NoSuchElementException(当文件末尾无更多token时)。

以下是两种正确的实现方式:

方法一:按行读取(直观易维护)

使用BufferedReader逐行读取文件内容,通过判断空行切换精灵:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> elfCalories = new ArrayList<>();
        elfCalories.add(0); // 初始化第一个精灵的卡路里总和
        int currentElfIndex = 0;

        try (BufferedReader reader = new BufferedReader(new FileReader("Elf.dat"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim(); // 处理空行含空格的情况
                if (line.isEmpty()) {
                    // 遇到空行,切换到下一个精灵
                    elfCalories.add(0);
                    currentElfIndex++;
                } else {
                    // 累加当前精灵的卡路里
                    int calories = Integer.parseInt(line);
                    elfCalories.set(currentElfIndex, elfCalories.get(currentElfIndex) + calories);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 找出最大卡路里值
        int maxCalories = 0;
        for (int calories : elfCalories) {
            if (calories > maxCalories) {
                maxCalories = calories;
            }
        }
        System.out.println(maxCalories);
    }
}

代码说明

  • 用ArrayList<Integer>动态存储每个精灵的卡路里总和,避免固定数组的资源浪费。
  • readLine()逐行读取内容,通过line.isEmpty()直接判断空行,先trim避免空行含空格的误判。
  • 空行触发精灵切换,非空行解析数字并累加至当前精灵的总和。

方法二:修改Scanner的分隔规则

若坚持使用Scanner,可修改分隔符以识别空行作为精灵分隔标记:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("Elf.dat"));
        // 设置分隔符:单个/多个空白(分隔同精灵数字)、两个及以上换行(分隔不同精灵)
        input.useDelimiter("(\\s+|\\n{2,})");

        int currentSum = 0;
        int maxCalories = 0;

        while (input.hasNextInt()) {
            int calories = input.nextInt();
            currentSum += calories;
            
            // 检查是否遇到精灵分隔的空行
            if (input.hasNext("\\n{2,}")) {
                maxCalories = Math.max(maxCalories, currentSum);
                currentSum = 0;
                input.next(); // 跳过空行分隔符
            }
        }
        // 处理最后一个精灵(文件末尾可能无空行)
        maxCalories = Math.max(maxCalories, currentSum);

        System.out.println(maxCalories);
        input.close();
    }
}

代码说明

  • useDelimiter("(\\s+|\\n{2,})")将分隔符设置为两类:\\s+匹配数字间的空白,\\n{2,}匹配空行。
  • 读取数字后检查空行分隔符,存在则更新最大值并重置当前总和。
  • 最后单独处理文件末尾的精灵,避免遗漏总和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:35:25