2015-10-16 65 views
0

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

     } 
    } 
} 
+4

你可以使用'int.TryParse'和检查它的有效整数,而不是抛出异常。然后你可以想要一个输入,直到你用'while'语句得到一个有效的输入。 –

+0

从catch再次调用main方法,如Main(new [] {string.Empty})。 – Mukund

+0

@Mukund多数民众赞成在奇怪和不必要的。简单的循环就足够了。 –

回答

3

尝试包裹在try-catch在类似

while(Console.Readline() != "q") 
{ 
... your code here ... 

} 

,那么你的应用程序将继续下去,直到你键入q并回车

8

,而不是try...catch块使用循环和intTryParse方法

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"); 
} 
+0

感谢米哈伊尔工作正常 – Sharon