user3806140
user3806140

Reputation: 5

Do while problems when trying to loop if condition is not attain

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

Answers (4)

Andrew Lapham
Andrew Lapham

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

Mike
Mike

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

user2054388
user2054388

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

barak manos
barak manos

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

Related Questions