Mark West Mark West - 5 months ago 39
C# Question

Odd/even number with the verification of an input

I'm trying to make a simple odd/even number program, but I want to compare did user entered number. When I enter any symbol which is not a number I get second exception, but when I just press enter ie. not giving any value, I still get a second except except the first one, which I'm trying to get when I don't give any value. My question is how to get a first exception text when I just press enter, since right now I only get second one, whatever I enter.

Console.WriteLine("Enter a number: ");
try
{
var number = int.Parse(Console.ReadLine());
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");

else
Console.WriteLine($"Entered number {number} is odd.");
}
catch (ArgumentNullException)
{
Console.WriteLine("You need to enter some value.");
}

catch (Exception)
{
Console.WriteLine("You need to enter a number.");
}

Answer Source

You should catch FormatException in case you just press enter as string.Empty is being passed to int.Parse. ArgumentNullException is being thrown only if the input value which was passed to int.Parse is null. Here is example how you can do this and write different messages depending on the inputed value:

Console.WriteLine("Enter a number: ");
string input = Console.ReadLine();
try
{
    var number = int.Parse(input);
    if (number % 2 == 0)
        Console.WriteLine($"Entered number {number} is even.");

    else
        Console.WriteLine($"Entered number {number} is odd.");
}
catch (FormatException exc)
{
    if(string.IsNullOrEmpty(input))
    {
        Console.WriteLine("You need to enter some value.");
    }
    else
    {
        Console.WriteLine("You need to enter a number.");
    }

}

catch (Exception exc)
{
    Console.WriteLine("You need to enter a number.");
}