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

Java中返回int数组时报“方法必须返回int[]类型”如何解决

报错根因

你遇到的This method must return a result of type int[]报错,核心是checker方法声明了返回int[]类型,但存在未覆盖的代码执行路径没有返回值:当文件存在但为空、或无有效可读取行时,不会进入while循环执行返回逻辑,try块执行完成后没有对应返回值,不符合Java方法的语法要求。

除此之外你的代码还存在两个隐藏bug:

  • Scanner.nextLine()已经读取了单行内容,用\n分割单行内容得到的数组长度永远为1,调用moreData[1]会直接抛出数组越界异常
  • while循环内的return语句会直接跳出方法,导致后续的myReader.close()永远不会执行,造成资源泄漏
修复方案

调整说明

  • 补全所有代码分支的返回值,兜底返回默认数组
  • 修正内容读取逻辑:根据你预期输出{0,40}两个元素的需求,适配两种常见的文件存储格式
  • 使用try-with-resources语法自动释放Scanner资源,无需手动关闭
  • 补充格式异常、数字转换异常的捕获兜底,避免运行时崩溃

修复后代码

适配场景1:Tracker.txt一行存两个数字,用空格/制表符分隔(比如0 40)

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

public class ReadFile {
    public static int[] checker(){
        // try-with-resources自动关闭Scanner,避免资源泄漏
        try (Scanner myReader = new Scanner(new File("Tracker.txt"))) {
            if (myReader.hasNextLine()) {
                String data = myReader.nextLine().trim();
                // 按任意空白符分割内容
                String[] moreData = data.split("\\s+");
                int day = Integer.parseInt(moreData[0]);
                int posts = Integer.parseInt(moreData[1]);
                return new int[] {day, posts};
            }
            // 文件为空时返回默认值
            return new int[]{0, 0};
        } catch (FileNotFoundException e) {
            // 文件不存在时返回默认值
            return new int[]{0, 0};
        } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
            // 文件内容格式不符合要求时返回默认值,可根据业务需求调整
            return new int[]{0, 0};
        }
    }
}

适配场景2:Tracker.txt每行存一个数字,第一行是day,第二行是posts

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

public class ReadFile {
    public static int[] checker(){
        try (Scanner myReader = new Scanner(new File("Tracker.txt"))) {
            if (myReader.hasNextLine()) {
                int day = Integer.parseInt(myReader.nextLine().trim());
                if (myReader.hasNextLine()) {
                    int posts = Integer.parseInt(myReader.nextLine().trim());
                    return new int[] {day, posts};
                }
            }
            return new int[]{0, 0};
        } catch (FileNotFoundException e) {
            return new int[]{0, 0};
        } catch (NumberFormatException e) {
            return new int[]{0, 0};
        }
    }
}

修复后你可以直接在其他类调用ReadFile.checker()获取int数组,用于后续的if判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:21:02