我要求用户为他们的年龄输入一个int,但程序在输入字符串时会崩溃(显然)。
我如何允许他们输入字符/字符串,但程序显示有趣的消息然后退出?
这是我到目前为止所得到的:
Console.WriteLine("Please can you enter your age");
int userage = Convert.ToInt32(Console.ReadLine());
if (userage < 16)
{
var underage = new underage();
underage.text();
}
else if (userage>122)
{
Console.WriteLine("No one has ever reached this age and so you can't possibly be this old");
Console.WriteLine("Please enter a different age next time!");
Console.WriteLine("Unless you really are this old, in which case don't work!!");
Console.WriteLine("Press any key to exit the program.\n");
Environment.Exit(0);
}
else if(userage<122)
{
Console.WriteLine("Ah brilliant, you are old enough to use our services\n");
Console.WriteLine("We shall continue as first planned\n");
}
else
{
}
答案 0 :(得分:2)
尝试:
Console.WriteLine("Please can you enter your age");
int userage;
if (int.TryParse(Console.ReadLine(), out userage))
{
//your if block
}
else
{
Console.WriteLine("Your input is funny and I am a funny message\n");
Environment.Exit(0);
}