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

循环迭代中复用方法输出的Java程序问题排查

问题修复:让myCalculations的结果能传递到下一次调用

嘿,我一眼就发现你的问题根源了——你把aliveSoldiers数组定义在处理每行的循环内部,每次循环都会重新创建一个全新的数组,还把前两个元素重置成首行的初始值,之前调用myCalculations得到的结果自然就被覆盖掉了!

具体哪里出问题了?

看这段关键代码:

while ((otherElement = in.readLine()) != null) {
    // ... 其他代码
    int[] aliveSoldiers = new int[100]; // 划重点!每次循环都新建数组
    aliveSoldiers[0] = results[0]; // 每次都重置成首行的初始值
    aliveSoldiers[1] = results[1];
    // ... 调用方法、修改aliveSoldiers
    // 循环结束后,这个aliveSoldiers就被销毁了,下一次循环又重来
}

相当于你每次循环都从头初始化士兵数,之前的更新完全没被保留,当然没法传到下一次调用啦。

怎么修复?

核心思路就是:把保存当前士兵数的变量(或数组)移到循环外面初始化,循环内部只更新它,而不是每次都新建。这里我用两个单独的变量代替数组,代码更简洁易懂:

优化后的完整代码片段

// 先从首行获取初始士兵数,存在循环外的变量里
int currentSoldier1 = results[0];
int currentSoldier2 = results[1];

// 处理剩余行的循环
String otherElement = null;
try {
    while ((otherElement = in.readLine()) != null) {
        System.out.println("Line to process:\t\t\t" + otherElement);
        String[] arr = otherElement.split(" ");
        
        for (int k = 0; k < arr.length; k++) {
            try {
                int days = Integer.parseInt(arr[k]);
                System.out.println("number of days: \t\t\t" + days);
                
                // 用当前的士兵数调用方法
                String returnAliveSoliders = myCalculations(currentSoldier1, currentSoldier2, days);
                System.out.println(returnAliveSoliders);
                
                // 解析返回结果,直接更新当前士兵数
                String[] newItems = returnAliveSoliders.split(" ");
                currentSoldier1 = Integer.parseInt(newItems[0]);
                currentSoldier2 = Integer.parseInt(newItems[1]);
                
                System.out.println("Updated alive soldiers: " + currentSoldier1 + ", " + currentSoldier2);
            } catch (NumberFormatException nfe) {
                System.out.println("Oops, invalid number in line element: " + arr[k]);
                nfe.printStackTrace();
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

额外小建议

  • 别用长度100的数组存几个值啦,用对应数量的变量或者ArrayList更灵活高效。
  • 异常处理可以更精准,比如打印出出错的具体元素,方便你调试。
  • 可以把“字符串转整数”的逻辑抽成一个小方法,避免重复写try-catch。

这样修改后,每次调用myCalculations得到的新士兵数,都会被保存下来,作为下一次调用的前两个参数,完美符合你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:20:42