Saisano
Saisano

Reputation: 49

While loop not producing correct results

I am trying to use a while-loop to ask the user for a number between 1 and 10. While the user fails to enter a number between 1 and 10 (inclusive), I want to ask them for another number.

My code so far is:

int i = 0;
Console.WriteLine("Enter a number.");
while (i <= 10)
{
    Console.ReadLine();

    if (i > 1 && i < 10)
    {
        Console.ReadLine();
        continue;
    }

    if (i < 1 && i > 10)
    {
        Console.WriteLine("Enter New Number...");
        break;
    }

    Console.ReadLine();
}

What am I doing wrong?

Upvotes: 2

Views: 421

Answers (7)

Gabe
Gabe

Reputation: 86848

Is if (i > 1 && i < 10) really what you want? It checks to see if a number is greater than 1 and less than 10. What if the number is 1 or 10?

Upvotes: 1

cpx
cpx

Reputation: 17587

Untested code

int i = 0;
int count = 0;

Console.WriteLine("Enter a number.");
while (count <= 10)
{
   i = Convert.ToInt32(Console.ReadLine());

   if (i > 1 && i < 10)
   {
       count++;
       continue;

   }
   if (i < 1 || i > 10)
   {
      Console.WriteLine("Enter New Number...");
      continue;
   }
}

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28894

int i = 0;
while (i < 1 || i > 10)
{
    int.TryParse(Console.ReadLine(),out i);
}

or with text

int i = 0;
Console.WriteLine("Enter a number");
int.TryParse(Console.ReadLine(),out i);
while (i < 1 || i > 10)
{
    Console.WriteLine("Try Again");
    int.TryParse(Console.ReadLine(),out i);
}

:)

Upvotes: 4

Joel Etherton
Joel Etherton

Reputation: 37543

Along with the conditional being incorrect, it should be:

if(i < 1 || i > 10)

You're also not assigning i to be anything. You use Console.ReadLine() but you're not actually dumping it into i. This drops you into an infinite loop.

You also run the risk of type issues if the value you're receiving isn't an integer. You should perform some type conversions and numeric checks to prevent casting problems.

Upvotes: 0

Lucero
Lucero

Reputation: 60276

Two things:

  • You never assign anything but 0 to i - so that it will never actually change. You need to parse the user input.

  • (i < 1) && (i > 10) can never be true, you may want to use the logical or operator || instead.

Upvotes: 1

n00b
n00b

Reputation: 5732

if (i < 1 && i > 10)

to

if (i < 1 || i > 10)

Upvotes: 1

SLaks
SLaks

Reputation: 888283

You're writing if (i < 1 && i > 10).
i can never be both less than 1 and more than 10.
(Hint: 'and' is the wrong word)

Also, you never assigned a value to i.
(Hint: call int.Parse)

Also, you probably want to swap break (which stops looping) and continue (which continues looping)

Also, what should the condition in the while loop be?

Upvotes: 15

Related Questions