How to make this piece of code loop asking for input from the user until int.TryParse()
is successful?
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
System.Console.WriteLine("You must enter an integer type value"); 'need to make it ask user for another input if first one was of invalid type'
}
Version of the code after the helpful answer:
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
{
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
x = temp2;
}
}
Even though the question has been already marked as answered,
do-while
loops are much better for validating user input.Notice your code:
You have the same code at top and bottom. This can be changed:
edit:
Try this. I personally prefer to use
while
, butdo .. while
is also valid solution. The thing is that I don't really want to print error message before any input. Howeverwhile
has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to usegoto
even tho some people would probably track me down and slap me with a fish because of it.I've been wondering quite a lot, but I just figured it out!
This code will loop until the user has entered an integer number. This way, the program doesn't simply report an error, but instead immediately allows the user to input again another, correct value.