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

如何限制行星选择输入的取值范围为1至8?

如何限制行星选择输入的取值范围为1至8?

嘿,我懂你碰到的麻烦啦——因为咱们要的是整数输入,确实没法用字符串的Length属性来限制范围。别担心,咱们可以用输入验证循环来搞定这个问题,既能保证输入是有效的整数,又能把数值牢牢限定在1到8之间。

给你两种实用的实现方式,选你觉得顺手的就行:

方式一:无限循环+条件跳出

这种写法逻辑清晰,直到用户输入符合要求才结束循环:

static void Main(string[] args)
{
    // Choose a planet
    int planet = 0;
    while (true)
    {
        Console.WriteLine("Choose a planet number (1 - Mercury / 2 - Venus / 3 - Earth / 4 - Mars / 5 - Jupiter / 6 - Saturn / 7 - Uranus / 8 - Neptune): ");
        // 用TryParse避免非整数输入导致程序崩溃
        if (int.TryParse(Console.ReadLine(), out planet) && planet >= 1 && planet <= 8)
        {
            break; // 输入合格,跳出循环
        }
        else
        {
            Console.WriteLine("Invalid input! Please enter a number between 1 and 8.");
        }
    }

    // Your Age
    Console.WriteLine("How old are you?");
    int userAge = Convert.ToInt32(Console.ReadLine());
    // 这里可以继续编写后续业务逻辑
}

方式二:Do-While循环

这种写法会先执行一次输入操作,再判断是否需要继续循环,逻辑更紧凑:

static void Main(string[] args)
{
    // Choose a planet
    int planet;
    bool isInputValid;
    do
    {
        Console.WriteLine("Choose a planet number (1 - Mercury / 2 - Venus / 3 - Earth / 4 - Mars / 5 - Jupiter / 6 - Saturn / 7 - Uranus / 8 - Neptune): ");
        // 同时验证输入是否为整数,以及是否在1-8范围内
        isInputValid = int.TryParse(Console.ReadLine(), out planet) && planet >= 1 && planet <= 8;
        if (!isInputValid)
        {
            Console.WriteLine("Oops, that's not valid! Please pick a number from 1 to 8.");
        }
    } while (!isInputValid);

    // Your Age
    Console.WriteLine("How old are you?");
    int userAge = Convert.ToInt32(Console.ReadLine());
    // 后续逻辑编写处
}

关键要点说明

  • 用int.TryParse替代Convert.ToInt32:如果用户输入的不是数字(比如字母、特殊符号),TryParse会返回false,不会抛出异常导致程序崩溃,还能友好提示用户重新输入。
  • 范围判断planet >=1 && planet <=8:直接对整数数值做判断,精准限定输入范围,这才是针对整数类型的正确做法。

备注:内容来源于stack exchange,提问作者frostsxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 14:27:56