2016-10-11 8 views
0

사용자에게 나이를 입력하도록 요청했지만 문자열을 입력 할 때 프로그램이 충돌합니다 (분명히).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 변수는 유효한 값을 가지며 false이면 사용자 입력이 유효한 정수가 아님을 알 수 있습니다. –

답변

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); 
      } 
관련 문제