Ok what I am trying to do seems fairly simple, yet it’s not working the way I want it. I know I’m just not getting something. Essentially I am trying to read console input, assign it to a variable. Then I want to check that variable to see if it is a valid number. If it’s not, I want to tell the user it is invalid and start the loop over again until I get a valid number, then exit. Here is my code, can you please help me understand what I am doing wrong?
const int AVERAGE_IQ = 100;
int userIQ;
bool done = false;
do
{
Console.Write("Please enter an IQ Score between 1 and 200: ");
userIQ = Convert.ToInt32(Console.ReadLine());
if (userIQ == 0 || userIQ >= 200)
{
Console.WriteLine("You have entered an invalid IQ Score, please try again.");
done = false;
}
else if (userIQ >= AVERAGE_IQ)
{
Console.WriteLine("{0} is an above average IQ.", userIQ);
done = true;
break;
}
else if (userIQ <= AVERAGE_IQ)
{
Console.WriteLine("{0} is an below average IQ.", userIQ);
done = true;
break;
}
else if (userIQ == AVERAGE_IQ)
{
Console.WriteLine("{0} is anaverage IQ.", userIQ);
done = true;
break;
}
} while (done =! true);
=!should be!=You’re doing an assignment, setting done to false. Since:
while (done =! true);is the same aswhile (done = !true);which is the same aswhile (done = false);On each iteration, you’re assigning done to be false, which itself evaluates to false, which means your loop will never iterate a second time.
Change the loop expression to either
while (done != true);or better yetwhile (!done);