tags:

views:

220

answers:

7

The question is : 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), 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?

+13  A: 

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?

SLaks
best answer ;) it teaches not gives the ready code on a plate ^^
n00b32
thank you for your help ^^
Saisano
+1  A: 
if (i < 1 && i > 10)

to

if (i < 1 || i > 10)
n00b32
+1  A: 

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.

Lucero
A: 

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.

Joel Etherton
+3  A: 
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);
}

:)

Paul Creasey
Thank you for your help!
Saisano
A: 

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;
   }
}
Dave18
Thank you for your help
Saisano
+1  A: 

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?

Gabe
he wants the number to be between 1 and 10.
Dave18
The wording "enter a number between 1 and 10 (inclusive)" leads me to believe that 1 and 10 should be considered part of the range.
Gabe