hassy786 hassy786 - 12 days ago 7x
C# Question

Why wont it let me move to the next piece of code?

I have written a do while loop that will only allow a currency between £0.90 and £10 to go through and it works fine however even though I enter a valid currency such as £5 or £0.90, it will not go to the next set of code which will tell the user how much they have and what product they want to purchase... It is my first attempt to try this code out so maybe I have missed something out from it?

decimal moneytospend;

Console.WriteLine("Enter Currency between £0.90 and £10");
while (decimal.TryParse(Console.ReadLine(), out moneytospend) ||
(moneytospend < 0.90M || moneytospend > 10.00M));

Console.WriteLine("You have £" + moneytospend + " to spend."); /// <== never gets here


The problem is the condition for your "while" loop.

while (decimal.TryParse(Console.ReadLine(), out moneytospend)....

This will be true whenever the user enters a valid decimal (even if the number is in the range you're looking for), so it's essentially an infinite loop. The only way you can get beyond this point is if the user enters something other than a decimal (i.e. they enter invalid input).

Replace the first || with && (like below) and it should work:

while (decimal.TryParse(Console.ReadLine(), out moneytospend) && (moneytospend < 0.90M || moneytospend > 10.00M))