2

So I'm making a little text game, and I need the user to enter an integer when it asks for grid size. And if an integer isn't entered I want the question to be asked again.

Right now I have:

Console.WriteLine("Enter Grid Size.");
int gridSize = int.Parse(Console.ReadLine());

I need a way to check if the input is a integer, and then ask again if it's not. Thanks

Joey Weidman
  • 373
  • 2
  • 4
  • 9

2 Answers2

7

You can use int.TryParse instead:

int gridSize;
Console.WriteLine("Enter Grid Size.");
while(!int.TryParse(Console.ReadLine(), out gridSize))
{
    Console.WriteLine("That was invalid. Enter a valid Grid Size.");
}

// use gridSize here
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4

You can use TryParse:

var input = 0;
if(int.TryParse(Console.ReadLine(), out input)
{
}
Peyman
  • 3,068
  • 1
  • 18
  • 32