Reputation: 5
I'm trying to have my program work by inputting an integer between 10-50 and if they didn't input within the acceptable range the loop will go back by making them input again. But I can't seem to understand why my program doesn't work. I know the logic behind but I think the codes is the problem. Here is my code
Console.WriteLine("Enter a digit between 10 and 50 ");
xx = Console.ReadLine();
x = int.Parse(xx);
do
{
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
Upvotes: 0
Views: 260
Reputation: 478
Check your IF and WHILE conditions.. Try this:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x <= 10 || x >= 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 || x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
Upvotes: 0
Reputation: 633
How about this:
string xx;
int x;
Console.WriteLine("Enter a digit between 10 and 50 ");
bool cont = true;
do
{
xx = Console.ReadLine();
if (int.TryParse(xx, out x) && 10 <= x && x <= 50)
cont = false;
else
Console.WriteLine("Pleae input again: ");
}
while (cont);
Seeing while(true)
makes my skin crawl. And, you should always use int.TryParse
instead of int.Parse
for user input.
Upvotes: 3
Reputation: 115
You need to ask for the input each time or you wont come out of the loop.
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
Upvotes: -1
Reputation: 30136
The if
condition is wrong, and the while
condition is wronger!
Try this instead:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (10 <= x && x <= 50)
break;
Console.WriteLine("Pleae input again: ");
}
while (true);
Upvotes: 3