Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
within my code there is error i cant seem to find. as you can see by my code a value of 1 or 0 needs to be entered (otherwise a message occurs and asks for the value to be re-entered) however this message keeps repeating constantly.

C#
Console.WriteLine("Please enter first value: ");
iValue1 =
    Convert.ToInt16(Console.ReadLine());
while (iValue1 > 1)
{
    Console.WriteLine("Sorry value must be 1 or 0. Please re-enter value: ");
}



i can't seem to find out how to fix this, this happens for all three values i am using.

Preview of Problem:
http://i.imgur.com/WAcT2Ho.png?1[^]
Posted
Updated 18-Dec-13 17:47pm
v2
Comments
Sunny_Kumar_ 19-Dec-13 0:37am    
seems to work fine... show me the declaration of "iValue1" variable.

I guess this line

C#
iValue1 =
    Convert.ToInt16(Console.ReadLine());


must come again inside the while loop to get the fresh input from the user.

C#
Console.WriteLine("Please enter first value: ");
iValue1 =
    Convert.ToInt16(Console.ReadLine());
while (iValue1 > 1)
{
    Console.WriteLine("Sorry value must be 1 or 0. Please re-enter value: ");
    iValue1 = Convert.ToInt16(Console.ReadLine());

}
 
Share this answer
 
Comments
Member 10475849 19-Dec-13 0:44am    
Thank you :) this seemed to fix my problem :D
Hi, I am not able to reproduce your issue. at console i enter 1 and click enter button, i do not see error message. It seems some thing is wrong with your code, Can you provide the complete code of main method

C#
public static void Main(string[] args)
       {
           int iValue1;
           Console.WriteLine("Please enter first value: ");
           iValue1 =
               Convert.ToInt16(Console.ReadLine());
           while (iValue1 > 1)
           {
               Console.WriteLine("Sorry value must be 1 or 0. Please re-enter value: ");
           }
           Console.ReadLine();


I thought earlier that you are getting this error when you enter 1 or 0, you have not mentioned explicitly when this error is coming.

Reason of your error is 'while loop' Say you entered 5 then while loop will keep on running as condition while (iValue1 > 1) always true
instead of while loop use If condition

As you have provided your code here is the solution: use do while instead of while loop as shown below

C#
do

{
    if (iValue1 > 1)
    {
        Console.WriteLine("Sorry value must be 1 or 0. Please re-enter value: ");
        iValue1 = Convert.ToInt16(Console.ReadLine());
    }
}
while (iValue1 > 1);
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900