问题
I'm fairly new to C#. I'm trying to make a basic program that converts Degrees in Celsius to Fahrenheit. But here's the catch, I want to make sure that the user inputs only a valid number and no characters or symbols. And if the user inputs, for example 39a,23, the Console asks him to enter the number again.
Console.WriteLine("Please enter the temperature in Celsius: ");
double x = Convert.ToDouble(Console.ReadLine());
Also, I've been making other programs, and I've been wondering - do I always have to use "Convert.ToInt/Convert.ToDouble"? or is there a faster way?
回答1:
It would be better you use the method Double.TryParse
. This way you will check if the string that user provided can be parsed to a double.
// This is the variable, in which will be stored the temperature.
double temperature;
// Ask the user input the temperature.
Console.WriteLine("Please enter the temperature in Celsius: ");
// If the given temperature hasn't the right format,
// ask the user to input it again.
while(!Double.TryParse(Console.ReadLine(), out temperature))
{
Console.WriteLine("The temperature has not the right format, please enter again the temperature: ");
}
The method Double.TryParse(inputString, out temperature)
will return true
, if the parsing is successful and false
if it isn't.
For more information about the method Double.TryParse
please have a look here.
来源:https://stackoverflow.com/questions/24801628/allow-to-only-input-a-number-c-sharp