gpt4 book ai didi

c# - 如何查看用户是否未在 C# 中输入有效条目

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:14 25 4
gpt4 key购买 nike

我想知道如果用户在下面的代码中输入了无效条目,如何输出。例如,如果他们输入字符串字符或字符串字符和数字的组合。现在,如果输入无效条目,它只会中断程序。请保留最基本方法的答案,因为我对编程还很陌生!

 Console.Write("Please enter the persons age: ");
int age = int.Parse(Console.ReadLine());
if(age == 17)
{
Console.WriteLine("That's to bad! You will have to wait until next year!");
}
else if (age < 18)
{
Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
}
else
{
Console.WriteLine("You are of age to be here.");
}

while (true)
{
Console.Write("Please enter the next persons age: ");
age = int.Parse(Console.ReadLine());

if (age == 17)
{
Console.WriteLine("That's to bad! You will have to wait until next year!");
}
else if (age < 18)
{
Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
}
else if (age > 18)
{
Console.WriteLine("You are of age to be here.");
}
else
{
Console.WriteLine("Please enter a valid entry");
}
}

最佳答案

你可以这样做:

int age;

if (int.TryParse(Console.ReadLine(), out age))
{
if (age > 17)
{
Console.WriteLine("That's too bad! You will have to wait until next year!");
}
// etc
}
else
{
Console.WriteLine("Please enter a valid input");
}

解释:

int.TryParse 是一种接受string 并尝试将其转换为int 的方法,如果转换成功则分配结果赋给age变量并返回true导致程序进入if block ,否则返回false并且程序进入否则 block 。 age 变量是通过使用 C# 的 output parameters feature 赋值的。这是一种将变量从外部传递给方法的方法,而后者 promise 会为其分配一些值。

关于c# - 如何查看用户是否未在 C# 中输入有效条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52617051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com