2016-10-11 31 views
0

ユーザーに年齢のintを入力するよう依頼していますが、文字列を入力するとプログラムがクラッシュします。C#ユーザーが整数の代わりに文字/文字列を入力するのを止めます。

char/stringを入力できるようにするにはどうすればよいでしょうか?面白いメッセージを表示して終了するには?

これは私がこれまで持っているものです:

 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'を返します。 trueの場合、int変数は有効な値を持ちます。falseの場合は、ユーザー入力が有効な整数ではないことがわかります。 –

答えて

1

は、try:

  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); 
      } 
関連する問題