2016-10-11 94 views
0

我要求用戶輸入一個int年齡,但程序崩潰時,他們輸入一個字符串(顯然)。C#停止用戶輸入一個字符/字符串,而不是整數

我該如何去允許他們輸入一個字符/字符串,但程序顯示一個有趣的消息,然後退出?

這是我這麼遠:

 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 
     { 

     } 
+3

使用['int.TryParse'](https://msdn.microsoft.com/en-us /library/f02979c7(v=vs.110).aspx) –

+0

在那段代碼中,我會添加int.TryParse? –

+0

開始閱讀用戶輸入之後。將'Console.ReadLine'存儲在一個字符串變量中,並將其用作'int.TryParse'的參數。 'Int.TryParse'返回一個'bool'。如果它是真的,則int變量將具有有效值,如果它爲假,則知道用戶輸入不是有效整數。 –

回答

1

嘗試:

  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); 
      } 
相關問題