lufee lufee - 3 months ago 9
C# Question

C# console.write showing statement

This is part of my code and I'm trying to make console.write to show new statement of "Please re-enter number greater than 20 : " only.

The problem is when I run my code it show "Please re-enter number greater than 20 : " as well as previous statement ("Enter amount of fuel used in litres : "). in one line.

How can I make it not to show first write statement ??

static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
do
{
Console.Write("Enter amount of fuel used in litres : ");
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputTemp

Answer

Move the line Console.Write("Enter amount of fuel used in litres : "); outside the while-loop. In your example it is inside the while loop, so it is repeated every time an incorrect answer is entered. If you move it in front of the loop, it will only be written once to the console.

...
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
do
{
    text = Console.ReadLine();
    ...