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

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

4

You can use TryParse:

var input = 0;
if(int.TryParse(Console.ReadLine(), out input)
{
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.