如何将用户输入限制为五位数字?

2024-01-09

我试图限制用户只能在 C# 控制台中输入 5 位数字。我的代码错误检查了用户,但由于某种原因,在我输入 6 位数字后,控制台在 while 循环启动后停止。有人可以帮我找出问题所在吗?先感谢您!

Console.WriteLine("Enter the the zip code of the contact.");
temp = int.Parse(Console.ReadLine());

while (Console.ReadLine().Length != 5)
{
    Console.WriteLine("Error. Zip code is not 5 digits. Please enter a valid number.");
    temp = int.Parse(Console.ReadLine());

    if (Console.ReadLine().Length == 5)
    {
        temp = int.Parse(Console.ReadLine());
        address.zipCode = temp;
    }
}

您正在多次访问控制台。检查捕获的输入的长度 -temp。尝试这个:

var temp = Console.ReadLine();
while (temp.Length > 5)
{
    Console.WriteLine("Error. Zip code is not 5 digits. Please enter a valid number.");
    temp = Console.ReadLine(); 
}

address.zipCode = int.Parse(temp);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将用户输入限制为五位数字? 的相关文章

随机推荐