1

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);
                 } 
4
  • What exception are you getting and what line does it say the exception occurs on? You need to examine that information. Commented Oct 17, 2018 at 16:23
  • int? n = Convert.ToInt32(Console.ReadLine()); Commented Oct 17, 2018 at 16:24
  • input string was not in correct format Commented Oct 17, 2018 at 16:25
  • The error is because you are trying to parse an empty string as a number. Never assume that user input data are clean. Also, for the int? type (and other value-types (e.g. structs)) you should do x.HasValue instead of comparing with null. Commented Oct 17, 2018 at 16:35

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.