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

Java自定义方法未正确填充数组,返回值存在null问题求助

问题分析与修复

核心bug

你写的stringArrayMaker方法里,for循环的终止条件错了:

for (int i = 0; i < amount; i++) {
}

amount是目标位置的球员总数,但你得遍历整个pos数组(所有球员的数量),而不是只看前amount个元素。这就导致很多位置匹配的球员没被检查到,结果数组里空着的位置自然都是null。

修复后的代码

把循环条件改成i < pos.length就行:

public static String[] stringArrayMaker(String[] ADP, int[] pos, int position) {
    int amount = (int) Arrays.stream(pos).filter(po -> position == po).count();
    String[] array = new String[amount];
    int tracker = 0;
    // 遍历全部球员,而不是仅前amount个
    for (int i = 0; i < pos.length; i++) {
        if (pos[i] == position) {
            array[tracker] = ADP[i];
            tracker++;
        }
    }
    return array;
}

更省心的写法(可选)

既然已经用了Stream统计数量,不如直接用Stream完成筛选和数组生成,不用手动管tracker和循环边界,不容易出错:

public static String[] stringArrayMaker(String[] ADP, int[] pos, int position) {
    return IntStream.range(0, pos.length)
            .filter(i -> pos[i] == position)
            .mapToObj(i -> ADP[i])
            .toArray(String[]::new);
}

内容的提问来源于stack exchange,提问作者that one kid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:52:16