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

Java控制台应用inputCapacity方法输入校验返回值异常问题

解决inputCapacity方法返回错误输入值的问题

你的问题出在递归调用没有赋值:当用户输入无效时,你调用了inputCapacity(),但没把这个新调用返回的正确值赋值给userResponse,所以方法最后返回的还是第一次输入的那个无效值。

修正方案1:修复递归逻辑

把递归调用的结果赋值给userResponse,这样新的有效输入会覆盖原来的无效值:

static int inputCapacity() {
    Scanner in = new Scanner(System.in);
    System.out.println("Indiquez le nombre de personnes (max 4) : ");
    int userResponse = in.nextInt();
    if (userResponse < 1 || userResponse > 4) {
        System.out.println("Saisissez un nombre valide (max 4).");
        // 把递归调用的结果赋值给userResponse
        userResponse = inputCapacity();
    }
    return userResponse;
}

注意:这种写法每次递归都会新建Scanner实例,虽然能运行,但存在冗余,更推荐用循环实现。

修正方案2:用循环代替递归(更优解)

用do-while循环可以避免递归的栈溢出风险,逻辑也更直观清晰:

static int inputCapacity() {
    Scanner in = new Scanner(System.in);
    int userResponse;
    do {
        System.out.println("Indiquez le nombre de personnes (max 4) : ");
        userResponse = in.nextInt();
        if (userResponse < 1 || userResponse > 4) {
            System.out.println("Saisissez un nombre valide (max 4).");
        }
    } while (userResponse < 1 || userResponse > 4);
    return userResponse;
}

这个写法会持续要求用户输入,直到输入符合1-4的范围,直接返回正确值,不会出现返回旧值的问题。

内容的提问来源于stack exchange,提问作者Cédric Leroy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:05:21