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

Java读取不定空格分隔的非CSV文件至堆的问题排查

解决方案

问题原因

你当前代码用hasNextLine()作为循环条件,但Scanner的next()、nextInt()方法是按空白字符(空格、换行、制表符等)分割元素,和行无关。这种判断逻辑与实际读取的元素数量不匹配,导致循环次数异常,出现跳过条目的情况。

两种可行解决办法

办法一:基于元素的循环判断

直接判断是否还有天体名称可以读取,只要存在下一个元素,就读取名称、x坐标、y坐标三个值,逻辑更准确:

while (inFile.hasNext()) {
    entName = inFile.next();
    entX = inFile.nextInt();
    entY = inFile.nextInt();
    Astro temp = new Astro(entName, entX, entY);
    entDistance = temp.calculateDistance(x, y);
    heap.enqueue(new Astro(entName, entX, entY, entDistance));
}

办法二:按行读取并正确分割

如果你倾向于按行处理,可以用正则\\s+(匹配一个或多个空白字符)分割每行内容,避免生成空字符串的token:

while (inFile.hasNextLine()) {
    String line = inFile.nextLine().trim();
    if (line.isEmpty()) continue; // 跳过可能存在的空白行
    String[] tokens = line.split("\\s+");
    entName = tokens[0];
    entX = Integer.parseInt(tokens[1]);
    entY = Integer.parseInt(tokens[2]);
    Astro temp = new Astro(entName, entX, entY);
    entDistance = temp.calculateDistance(x, y);
    heap.enqueue(new Astro(entName, entX, entY, entDistance));
}

这里trim()用来去除行首尾的空白(包括你文件每行开头的缩进),split("\\s+")会把连续的空格作为分隔符,直接得到[天体名, x坐标, y坐标]的有效数组,解决你之前分割后出现大量空元素的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:15:39