我刚刚在C#中编写了一个简单的代码,用于显示一条消息,将您的输入作为睡眠时间并根据该消息返回您是否休息得很好或不休息。返回主目录
问题是,只要你键入除整数以外的任何东西,它就会引发异常,所以我试图用try和catch方法来处理这个问题。 我希望我的代码在下次正确输入整数后再次返回评估。我怎样才能修改我的代码来做到这一点?
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("your name");
string name = Console.ReadLine();
Console.WriteLine("how many hours of sleep did you get");
try
{
int hoursOfSleep = int.Parse(Console.ReadLine());
Console.WriteLine("hello " + name);
if (hoursOfSleep > 8)
{
Console.WriteLine("you are well rested");
}
else
{
Console.WriteLine("you need sleep");
}
}
catch
{
Console.WriteLine("Invalid Hours !! ");
Console.WriteLine(" Enter hours in integer");
}
}
}
}
你可以使用'int.TryParse'和检查它的有效整数,而不是抛出异常。然后你可以想要一个输入,直到你用'while'语句得到一个有效的输入。 –
从catch再次调用main方法,如Main(new [] {string.Empty})。 – Mukund
@Mukund多数民众赞成在奇怪和不必要的。简单的循环就足够了。 –