返回主码

0 c#

我刚刚在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");
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*aev 8

而不是try...catch块使用循环和TryParse方法int

int hoursOfSleep;
while(!int.TryParse(Console.ReadLine(), out hoursOfSleep)
{
    Console.WriteLine("Invalid Hours !! ");
    Console.WriteLine(" Enter hours in integer");
}

Console.WriteLine("hello " + name);

if (hoursOfSleep > 8)
{
    Console.WriteLine("you are well rested");
}
else
{
    Console.WriteLine("you need sleep");
}
Run Code Online (Sandbox Code Playgroud)