Xenopod
Xenopod

Reputation: 37

How to prevent type conflicts in c#

I am having trouble with types in c#. I have an int input on a console application and I would like for a (non-numeral characters) string input to be put back into my existing but not pictured do while loop like an error. I don't want to convert nonnumeral string values to int, but rather want to protect my object from crashing and return it to the beginning of my loop when an unacceptable value (i.e. a alphabetic string value) is presented. 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 for a string input to be treated like an "even" number. I know this seems like an amateurish mistake, but I am actually at a loss... Any help is appreciated.

Upvotes: 3

Views: 149

Answers (3)

A. Harkous
A. Harkous

Reputation: 252

User inputs are always received as String, you can't avoid that because user can type any thing keyboard can write. So you have to parse it as you are doing but you miss catching two errors:

  1. String may not be in the correct form (may not be a number, i.e includes alphabetical characters)
  2. String may be a number greater than the max for Int32

so you just have 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 also use int.TryParse,they give the same result. check this question What is better: int.TryParse or try { int.Parse() } catch

Upvotes: 1

Rufus L
Rufus L

Reputation: 37020

I usually use int.TryParse() in these situations, just to be 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 the integer value if it succeeded. 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);

Upvotes: 2

Steve
Steve

Reputation: 502

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);

Upvotes: 0

Related Questions