0

I am trying to use an if statement and a int.tryparse to try and create a loop that keeps running until a proper integer is given. A friend of mine said it could be done using an the pieces I mentioned above. Yet I have my doubts, was wondering if anyone could either verify this works or help me figure it out.

so far I have

if (!int.TryParse(temp, out move)) 
{
    Console.WriteLine("Bad integer")
}

Looking at this I don't see how it would loop, I was thinking a while loop might work better but am at a loss as to how I would set one up.

Thanks in advance,

Jeff

2
  • Keeps running until a proper integer is given? By user? Commented Jan 22, 2015 at 6:37
  • what about this string temp = null; do{ if(temp != null)Console.WriteLine("Bad integer"); temp = Console.Readkey(); }while(int.TryParse(temp, out move); Commented Jan 22, 2015 at 6:40

5 Answers 5

4

Unless that's within a loop of some sort, continuously asking for a new temp value, it won't loop back for more.

The sort of thing you're looking for is:

temp = Console.ReadLine();
while (!Int32.TryParse(temp, out move))  {
    Console.WriteLine("Bad integer");
    temp = Console.ReadLine();
}
// move should be okay now.

though there's a lot you can do to improve, handling exceptions and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

Just for clarification, the while(!int.TryParse(temp, out move)) means that while int.TryParse fails (or returns false/null?), keep looping through?
@Jeff, yes. TryParse returns true if all is okay, so false means something went wrong. Using ! will invert that return value. In English, while didn't fail parsing.
0

@Jeff Simply using the int.TryParse won't make a loop. You will have to write it in a while loop as below -

while( //your condition)
{
  if (!int.TryParse(temp, out move)) 
  {
    Console.WriteLine("Bad integer")
  }
}

Comments

0
int move;

Console.Write("Enter int: ");
var temp = Console.ReadLine();

while (!int.TryParse(temp, out move))
{
    Console.Write("Enter int: ");
    temp = Console.ReadLine();
}

Comments

0

Try this -

    int j;
    while (!int.TryParse(Console.ReadLine(),out j))
    {
        Console.Write("Bad integer\n");
    }

Comments

0
int corectinteger;
int input = Console.ReadLine();
bool flag = true;
while (flag)
{
    if (input != corectinteger)
    {
        Console.WriteLine("Bad integer");
        input = Console.ReadLine();
    }
    else if (input == corectinteger)
        flag = false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.