How to prevent type collisions in C #

I am having problems with types in C #. I have an int input in a console application and I would like the input of a string (not numeric characters) to be put back into my existing but not pictured do while loop as an error. I don't want to convert nonnumeral string values ​​to int, but rather I want to protect my object from crashing and return it to the beginning of my loop when an unacceptable value is presented (such as an alphabetic string value). For example:

Console.WriteLine("Please input an odd number:");
int input1 = int.Parse(Console.ReadLine());
if (input1 % 2 == 0)
{
    Console.WriteLine("Please input an odd number.");
    //is even
}
else
{
    TotalOdd = TotalOdd + input1;
    TotalNumeral++;
    Console.WriteLine("Accepted.");
    //is odd
}

      

I would like the string input to be treated as an "even" number. I know this sounds like a dilettante mistake, but I'm at a loss ... Any help is appreciated.

+3


source to share


3 answers


User inputs are always accepted as String, you cannot avoid this because the user can enter whatever thing the keyboard can write. So you have to parse it as you do, but you missed two mistakes:

  • The string may not be in the correct form (it may not be a number, i.e. contain alphabetic characters)
  • String can be number greater than max for Int32

so you just need to add the following to your code:



     try {
        int input1 = Int32.Parse(Console.ReadLine());
     }
     catch (FormatException) {
        //not a number input
        continue;//iterate to the next
     }   
     catch (OverflowException) {
        //inform the user about the error...
        //if this often happens try parsing Int64.Parse
     } 

      

you can use int.TryParse as well, they give the same result. check this question Which is better: int.TryParse or try {int.Parse ()} catch

+1


source


I usually use it int.TryParse()

in these situations just to make sure the number entered is a valid integer. This method returns true

if the conversion succeeds and takes an int

out parameter , which will be set to an integer value if it succeeds. Then you can add the check that Steve has in his answer above:



int input;

do
{
    Console.Write("Please input an odd number: ");
} while (!int.TryParse(Console.ReadLine(), out input)
         || input % 2 == 0);

      

+2


source


The following code will loop until an odd number is entered, and then input1 will hold the odd value;

  int input1 = 0;
    do {
        Console.WriteLine("Please input an odd number:");
        input1 = int.Parse(Console.ReadLine());
    } while (input1 % 2 == 0);

      

0


source







All Articles