Home > database >  while loop conditions with more than 1 condition/condition type C#
while loop conditions with more than 1 condition/condition type C#

Time:11-06

Trying to get my while loop to have more than 1 condition , basically User inputs a height in numbers and the code continues etc. the height data will be pass down the code for later calculations.

Currently I have set it to when user doesn't enter a number (such as the Letter 'H') it enters a while loop for an error message. HOWEVER i want there to also be the condition that the height entered cannot be more than 3 and if say user enters 5, it also enters the loop for the error message. Currently when entering the loop user can retry and enter a number ( can enter letters will keep going back). in my while condition i have tried to add && (heightM >3) - (while (double.TryParse(userInput, out double heightM)&& (heightM <3) == false) - but doesnt seem to do what i want. in this case it ignores the tryparse, if user inputs 4 it loops correctly but if a letter , application crashes.

Im very new - still learning , sorry if this is a simple question : /

double height;
string userInput = Console.ReadLine().ToLower();
while (double.TryParse(userInput, out double heightM) && (heightM<3) == false)
{
    Console.Clear();
    Console.WriteLine("Incorrect value or input");
    Console.WriteLine("");
    Console.WriteLine("Enter Height in Meters only up to Maxmium of 3 meters");
    userInput = Console.ReadLine().ToLower();   
}

height = double.Parse(userInput);

CodePudding user response:

Using a while(true) loop, we can check the conditions and break out of the loop, or the loop will continue forever until a correct value is inputted.

double height;
double maxHeight = 3;
while (true)
{
    var userInput = Console.ReadLine();
    if (double.TryParse(userInput, out var heightM) && heightM <= maxHeight)
    {
        height = heightM;
        break;
    }

    Console.Clear();
    Console.WriteLine($"Please enter Height in Meters only up to maximum of {maxHeight} meters");
}
Console.WriteLine(height);

CodePudding user response:

Parsing a string that is not a number will result in the out variable set to 0, so your logic is flawed. Instead you should change it to

double heightM;
string userInput = Console.ReadLine().ToLower();
while (!double.TryParse(userInput, out heightM) || (heightM > 3))
{
    ....
}

The first change is used to have a single hejghtM variable, then the second change is how do we test the result of TryParse, if the parsing fails we could immediately enter the retry code. So the third change is using the || instead of && and this leads to the fourth change where we test for value bigger than three to enter the retry loop.

  •  Tags:  
  • c#
  • Related