Oh, 2 things: 1) It is a console application. 2 ) I know it is in danish, but it doesn't really matter, its just an example of asking for some input. The text and variables does not matter.
Alright, consider this simple input: It could be any sort of input question really.
Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
kundenummer = Convert.ToInt16(inputKnr);
Now, what if the customer types something wrong? Such as a letter. A try & catch would make sure the application does not break, but that is not the solution I want. I want it to say that you did it wrong, try again. Pretty classic right?
But what is the best way to solve this solution? I have thought of this:
bool fangetKundenummer = true;
while (fangetKundenummer)
{
Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
try
{
kundenummer = Convert.ToInt16(inputKnr);
fangetKundenummer = false;
}
catch
{
Console.WriteLine("Fejl. Prøv igen");
}
}
But it just doesn't seem like the right way to do it.
Also, just to mention it, this little application I am playing with has 4 input questions in a row. This would mean 4 times this nasty while() loop.
You could also write a function. Something like this (no reason to do it the right way, its just to illustrate a concept):
static void verifyInput()
{
try
{
Console.WriteLine("question");
input = Console.ReadLine();
kundenummer = Convert.ToInt16(input)
}
catch
{
Console.WriteLine("Wrong. Do it over");
verifyInput(); //start the function all over
}
}
But you'd have to write a function for each and every input question, even though they might ask exactly for the same! (meaning perhaps all asking for an integer; but with a different question and variable).
This doesn't seem much better than the while() solution.
Does anyone have a clever idea?