简体   繁体   中英

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.");
        }

Try this:

var str = Console.ReadLine();
if (string.IsNullOrEmpty(str))
{
    Console.WriteLine("You need to enter some value.");
}
else
{
    int number;
    if (!int.TryParse(str, out number))
    {
        Console.WriteLine("You need to enter a number.");
    }
    else
    {
        if (number % 2 == 0)
            Console.WriteLine($"Entered number {number} is even.");
        else
            Console.WriteLine($"Entered number {number} is odd.");
    }
}

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.");
}

If you don't enter any value, the value is not null but ""(empty string), that's why it's not an ArgumentNullException

Do how George Alexandria suggested

    string s = Console.ReadLine(); 
if(s == "")
{ Console.WriteLine("You need
    to enter some value."); }

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