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

Java for循环内try块输入非法时自动跳转下一轮迭代的问题排查

问题原因分析
  • 现有for循环的迭代逻辑是每轮固定对应i自增1,当try块中输入不合法抛出异常时,catch仅做错误打印,没有任何逻辑阻止i自增,所以会直接进入下一艘赛艇的回合。
  • 如果你的input是Scanner类,之前如果用过nextInt()这类方法没处理换行符,也会出现nextLine()直接读到空字符串的问题,这个也可以同步排查。
解决方案

你可以把固定迭代次数的for循环改成while循环,只有当前赛艇输入合法、操作完成后才将计数加1,修改后的代码示例如下:

int i = 0;
while (i < boats.length) {
    try {
        System.out.printf("BOAT %d TURN %n", i + 1);
        System.out.println("Type Y to throw your dice!");
        String diceThrow = input.nextLine();
        boats[i].setPosition(newRiver.Flow(boats[i].getPosition(), newDice.diceThrow(diceThrow)));
        System.out.println("boat position is at " + boats[i].getPosition());
        // 只有操作成功才进入下一艘赛艇
        i++;
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
        // 异常时i不自增,停在当前赛艇要求用户重新输入
    }
}
额外排查点

如果修改后还是出现自动跳过输入的情况,可以检查你在这段代码之前有没有调用过input.nextInt()、input.nextDouble()这类只读取内容不读取末尾换行符的方法,如果有需要在调用后加一行input.nextLine()吃掉残留的换行符,避免后续nextLine()直接读到空内容触发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:24:05