简体   繁体   中英

how to make user input int null value c#

I'm trying to make a program that takes a number and print it on screen but if the user press enter the code ask the user to enter the number again but instead it shows me a exception

Enter_No:
                 Console.WriteLine("enter number");
                 int? n = Convert.ToInt32(Console.ReadLine());
                 if (n == (int?)null)
                 {
                     goto Enter_No;
                 }
                 else
                 {
                     Console.WriteLine(n);
                 } 

Use int.TryParse :

int? num = null;
while(!num.HasValue)
{
    Console.WriteLine("Please enter an integer:");
    num = int.TryParse(Console.ReadLine(), out int i) ? i : new int?();
}

Console.WriteLine("Entered integer: " + num.Value);

Tim's solution is wonderfully compact. Here's why your attempt failed.

From MSDN , Convert.ToInt32() throws a FormatException if:

value does not consist of an optional sign followed by a sequence of digits (0 through 9).

The preferred approach is int.TryParse() , as it returns false if it's unable to parse the integer rather than throwing an exception.

While the goto keyword is supported in C#, there are few or no situations (depending on who you ask) where it's the best option for flow control. Tim's while loop is an excellent approach.

First, don't use Go To:

Second: Inspect your data and use tryparse:

        bool success = false;
        do
        {
            Console.WriteLine("enter number");
            var n = Console.ReadLine();
            if (n == null)
            {
                // goto Enter_No;
            }
            else
            {
                int typedNum;
                success = int.TryParse(n, out typedNum);
                Console.WriteLine(typedNum);                    
            }
        } while (!success);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM