lufee lufee - 3 months ago 15
C# Question

C# error message displayed based on text or number input

I'm trying to write line where if text (anything other than number) typed it shows error message that it is not number and ask user to type again.

Also I have implanted that number must be 20 or higher which works fine and when ever user input less than 20 it shows error message and ask user again..

so my problem is that it shows error message for everything including number less than 20 and text.

So how can I make else statement that shows different message if text is type rather than number?

static double InputFuel() {
double fFuel;
string text;
bool badValue = true;

Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
do {

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 a number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputFuel


I tried something like this but not working

else (!int.TryParse(text, out num) {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}

Answer

Firstly I would check if input is number and after that if number is greater than 20

static double InputFuel() {
    double fFuel;
    string text;
    bool badValue = true;

    Console.Write("Enter amount of fuel used in litres : ");
    //Check if fule entered is greater than 20, if not ask again
    do {

        text = Console.ReadLine();
    if (!double.TryParse(text, out fFuel) {
            Console.WriteLine("\n\t {0} is not a number  \n\n", text);
        }

        else if (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 a number greater than 20 : ");
        }
    } while (badValue);
    return fFuel;
}//end InputFuel
Comments