简体   繁体   中英

How to use same variable for string input in one case, and int input in another case? (C#)

Quick question how do I use same variable for string input in case and int input in another case. Here is what I mean by that, I have a problem where I need to constantly insert number and then put the addition of those numbers inside another variable. This inserting is inside do while loop, for me to exit the loop and to show the sum of those numbers, I need to type "OK" or "ok". I have a problem where I do not know how to use string variable for int inputs.

Here is my code:

string input= "";
            int sum = 0;
            do
            {
                Console.WriteLine("Insert the number or OK (ok) for exit: ");
                input = Console.ReadLine();

                sum += Convert.ToInt32(input); 
// this is where I get the error Input string was not in the correct fromat

            } while (input != "OK" && input != "ok");

            Console.WriteLine(sum)

If anyone knows how to help me with this, I would gladly appreciate it.

First identify that the user entered integer or not using int.TryParse() , if user entered integer then add it to the sum variable otherwise check the string

do
{
    Console.WriteLine("Insert the number or OK (ok) for exit: ");
    input = Console.ReadLine();
    //This will add number only if user enters integer.
    if(int.TryParse(input, out int number)
        sum += number

 } while (input != "OK" && input != "ok"); 

You have to test for OK before you try to convert to a number, because OK won't convert to a number

        string input= "";
        int sum = 0;
        while(true)
        {
            Console.WriteLine("Insert the number or OK (ok) for exit: ");
            input = Console.ReadLine();

            if("OK".Equals(input, StringComparison.OrdinalIgnoreCase)) //do a case insensitive check. Note that it's acceptable to call methods on constants, and doing a string check this way round cannot throw a NullReferenceException
              break;//exit the loop

            sum += Convert.ToInt32(input); 

        } 

        Console.WriteLine(sum);

You'll still get the error if the user enters input other than OK, that is not convertible to a number, but this is the crux of your current problem. I'll leave dealing with other garbages as an exercise for you...

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