简体   繁体   中英

Checking if input is correct data type in C#

What I would like is to basically have the user enter in a float, and then the system check that the input is indeed a float, and if it is then it will proceed with the code, and if it is not then the user will have to re-input the with the correct data type. Sorry for the beginners question, an example of the code is:

            Console.Write("Response Value > ");
            Response = float.Parse(Console.ReadLine())

            Ask_Count = Ask_Count + 1;
            if (Response > 0 && Response < 6)
            {
                Valid_Count = Valid_Count + 1;
            }

How would I go about the program checking to see if Response is a float?

Thank you.

Use float.TryParse for it.

Console.Write("Response Value > ");
if(float.TryParse(Console.ReadLine(), out Response)
{
    Ask_Count = Ask_Count + 1;
    if (Response > 0 && Response < 6)
        Valid_Count = Valid_Count + 1;
}
else
    Console.WriteLine("Number entered is not a float");

another is by using is float .

bool result = varName is float;

or

float x = 0;
bool result = float.tryParse(varname, out x);

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