M.hjespersen M.hjespersen - 1 year ago 64
C# Question

c# do-while loop not working as I need it to

I want my loop to repeat as long as width is under 0.5 (MIN_WIDTH) or above 5.0 (MAX_WIDTH) both are created as constant doubles.
When I write the number 0, it does repeat as it should, but if I write anything between 0.1 - 0.4 it skips the loop, why?

Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :");
widthString = Console.ReadLine();
width = double.Parse(widthString);
} while (width < MIN_WIDTH || width > MAX_WIDTH);

Answer Source

It seems that you experience problems with decimal and thousand separators: if in your current culture (e.g. in Russian RU-ru one) . is a thousand (not decimal) separator it ignores and you'll get 0.4 -> 04 -> 4 which will pass the condition.

Remedy: specify CultureInfo.InvariantCulture explictly

do {
  Console.Write($"Give the width of the window between {MIN_WIDTH} and {MAX_WIDTH}: ");
  widthString = Console.ReadLine();

  double width;

  if (!double.TryParse(widthString, 
                       out width))
} while (width < MIN_WIDTH || width > MAX_WIDTH);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download