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

C#中do-while循环内continue关键字失效问题咨询

问题分析:C# do-while循环中continue为何没实现错误检查?

我明白你的困惑了——你想在第三个do-while循环里用continue跳过非法日期(比如2月30日)并重新输入,但结果不仅没让循环重复,反而抛出了ArgumentsOutOfRangeException异常。咱们来拆解一下问题所在:

核心原因:continue的作用+循环条件的漏洞

你写的continue本身语法没问题,但它的作用是跳过当前循环剩余的代码,直接进入下一次循环的条件判断。问题出在你的循环终止条件上:

while (!correctInput || dateInput > 31 || dateInput < 1)

当用户输入一个格式合法但超过当月天数的日期(比如2024年2月30日),correctInput是true,dateInput也在1-31之间,所以这个while条件会被判定为false,循环直接终止了!continue根本没机会让循环继续执行,程序就直接走到创建DateTime对象的代码,自然抛出参数越界异常。

简单说:你没把“日期是否符合当月天数”这个校验逻辑加入到循环的终止条件里,导致非法日期也能通过循环检查。

修复方案:完善循环终止条件

我们需要把“日期是否匹配当月天数”也加入到循环的判断逻辑中,确保所有非法输入都能让循环继续执行。这里有两种清晰的写法:

写法一:拆分校验逻辑,用标志位控制循环

do {
    Console.WriteLine("\nSet a date :");
    correctInput = int.TryParse(Console.ReadLine(), out dateInput);
    bool isDateValid = false; // 默认日期非法

    if (!correctInput || dateInput < 1 || dateInput > 31) {
        Console.WriteLine("Incorrect Input!");
    } else {
        if (dateInput > DateTime.DaysInMonth(yearInput, monthInput)) {
            Console.WriteLine("The date doesn't reach that many!");
        } else {
            isDateValid = true; // 日期完全合法
        }
    }
    // 循环继续的条件:输入格式错误 或 日期范围错误 或 日期超过当月天数
} while (!correctInput || dateInput < 1 || dateInput > 31 || !isDateValid);

写法二:整合所有校验条件,更简洁

do {
    Console.WriteLine("\nSet a date :");
    bool isInputFormatValid = int.TryParse(Console.ReadLine(), out dateInput);
    bool isDateInRange = isInputFormatValid && dateInput >= 1 && dateInput <= 31;
    bool isDateMatchMonth = isDateInRange && dateInput <= DateTime.DaysInMonth(yearInput, monthInput);

    if (!isInputFormatValid) {
        Console.WriteLine("Incorrect Input!");
    } else if (!isDateInRange) {
        Console.WriteLine("Date must be between 1 and 31!");
    } else if (!isDateMatchMonth) {
        Console.WriteLine("The date doesn't reach that many!");
    }
    // 只要有一个条件不满足,就继续循环
} while (!isInputFormatValid || !isDateInRange || !isDateMatchMonth);

额外小建议

其实你也可以尝试用try-catch直接捕获DateTime构造时的异常,但对于这种明确的输入校验,先做前置检查会比异常捕获更高效,代码可读性也更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:27:45