Dominik
Dominik

Reputation: 299

How I get the right exception for wrong Datatype input?

Sorry, first of all, I´m new in C# I´m trying to get the right way to handle the wrong input! In my small calculator I have ints for the input and to calculate with, but I how do I handle it when I have an input like: "hi", what is not an int? AND I want to loop if you make a wrong input again and I don´t know how to loop it....

Isn´t there anything like: if (x != int32) ?
I have tried it this way:

               Console.WriteLine("Enter the first number: ");
               while (!Int32.TryParse(Console.ReadLine(), out x))
               {
                   Console.WriteLine("Invalid input! Try again");
                   if (Int32.TryParse(Console.ReadLine(), out x))
                   {
                       break;
                   }
                }

Upvotes: 1

Views: 1468

Answers (1)

TheGeneral
TheGeneral

Reputation: 81533

You only need the following

int x;

Console.WriteLine("Enter the first number: ");
while (!Int32.TryParse(Console.ReadLine(), out x))
   Console.WriteLine("Invalid input! Try again");

Console.WriteLine($"You had one job and it was a success : {x}");

Here is the deal

Console.ReadLine() returns a string, Int32.TryParse( returns true or false if it can parse a string to an int.

The loop will continually loop while Console.ReadLine() cannot be parsed to an int

As soon as it can, the loop condition is not met and execution continues to the last Console.WriteLine

Upvotes: 2

Related Questions