简体   繁体   中英

C# How set a non-numeric value to 0

I have to write a code that will ask for 3 integers values and find the greatest one. However, if the user enters a non numeric value this must have the value of zero. So far i wrote this

        int a, b, c;

        Console.WriteLine("Enter value 1:");
        a = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter value 2:");
        b = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter value 3:");
        c = Convert.ToInt32(Console.ReadLine());

        if (a > b && a > c)
        {
            Console.WriteLine("The greatest value is: {0}", a);
        }
        if (b > a && b > c)
        {
            Console.WriteLine("The greatest value is: {0}", b);
        }
        if (c > a && c > b)
        {
            Console.WriteLine("The greatest value is: {0}", c);
        }

This code works only with numbers. My problem is that i can't make a non numeric input have the value of zero. I tried using string instead of int, so there is no error but i can not make use ">" with strings in the if statements and i also tried using as default, because when is default so it is zero.

Thank you

You can just replace:

x = Convert.ToInt32(Console.ReadLine());

With...

int.TryParse(Console.ReadLine(), out int x);

If the input can't be parsed, x will end up being 0.

I think you can create a function that does the try catch, in this way you print a message saying that the input was not a number.

static int Check(string input)
        {
            int result;
            try
            {
                result = Convert.ToInt32(input);
            }
            catch (FormatException e)
            {
                Console.WriteLine("Input not integer, the value assigned is 0");
                result = 0;
            }
            return result;
        }

For implementing you just call:

a = Check(Console.ReadLine());

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