How do I prevent crashing from invalid user input?

后端 未结 3 995
北恋
北恋 2021-01-25 15:06

I have encountered a problem where my program crashes due to the input of the user not following the variable data type. What I am asking the user to do is register some data f

相关标签:
3条回答
  • 2021-01-25 15:23
    bool ok = false;
    int release;
    while (!ok)
     {
       Console.Write("Ange release: ");
       ok = int.TryParse(Console.ReadLine(), out release);
       ok = ok && (release >= 1000) && (release <= 2050);
     }
    
    0 讨论(0)
  • 2021-01-25 15:23

    Use TryParse instead.

    Console.Write("Ange release: ");
    int release;
    while (!int.TryParse(Console.ReadLine(), out release))
    {
        Console.Write("Ange release: ");
    }
    
    0 讨论(0)
  • 2021-01-25 15:32

    Use Int32.TryParse() and handle the case when it's not an integer. The return value indicates whether the operation succeeded.
    For more information see http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

    0 讨论(0)
提交回复
热议问题