Respuesta :
Here's a solution in C#:
static int AskNumber(string prompt = "Please enter a number: ") { int number; bool numberOK = false;
do { Console.WriteLine(prompt); var numberString = Console.ReadLine(); numberOK = int.TryParse(numberString, out number); } while (!numberOK);
return number;
}
If you want to replace the default argument approach with function overloading, you change the function heading to:
static int AskNumber(string prompt ) {
// rest stays the same
}
And add this overload:
static int AskNumber() { return AskNumber("Please enter a number"); }
The compiler will figure out which one to call, so both these will work:
static void Main(string[] args) { AskNumber("Input some digits"); AskNumber(); }
static int AskNumber(string prompt = "Please enter a number: ") { int number; bool numberOK = false;
do { Console.WriteLine(prompt); var numberString = Console.ReadLine(); numberOK = int.TryParse(numberString, out number); } while (!numberOK);
return number;
}
If you want to replace the default argument approach with function overloading, you change the function heading to:
static int AskNumber(string prompt ) {
// rest stays the same
}
And add this overload:
static int AskNumber() { return AskNumber("Please enter a number"); }
The compiler will figure out which one to call, so both these will work:
static void Main(string[] args) { AskNumber("Input some digits"); AskNumber(); }