Im wanting to call a method twice where the user has to input two positive doubles. I then want those to be returned to the main() and displayed. I'm unsure how to call the method from the main as I have only done this using methods with 1 type of input.
public static void Main(string[] args)
{
double costLitres = VolumeAndCost();
}
public static double VolumeAndCost(double costLitres)
{
double litresOfFuel;
double costOfFuel;
Console.WriteLine("Please Enter The Number Of Litres Of Full Put Into Car.");
litresOfFuel = Convert.ToDouble(Console.ReadLine());
if (litresOfFuel > 0)
{
return litresOfFuel;
}
else
{
Console.WriteLine("Please enter a positive value.");
litresOfFuel = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine("Please Enter The Cost Of The Fuel In Dollars And Cents.");
costOfFuel = Convert.ToDouble(Console.ReadLine());
if (costOfFuel > 0)
{
return costOfFuel;
}
else
{
Console.WriteLine("Please enter a positive value.");
costOfFuel = Convert.ToDouble(Console.ReadLine());
return costOfFuel;
}
I think the
VolumeAndCost()is too complex to be able to reuse. It does mutiple things. Try to separate them in much simplere functions which can be reused.About the example:
For example the
AskPositiveDouble();method will loop util the criterea "is double and positive". Otherwise it will ask again. In future, there will be a situation that the user should be able to cancel this all. That will be the next step. (double? litersand when it returns a default0in this case)_, you can stop the program.VolumeAndCostis not that special, but using a separate method can have some benefits, that where you want to calculate the price, it's on one spot of the code. (for example if you want to add tax, later you only need to change that method.)Tip: Try to avoid using
Convert.ToDouble(). When the value is not a double, it will raise an exception. You should avoid exceptions as much as possible; It disrupts the good flow in your application.double.TryParse()is here to help. It returnsfalsewhen the string doesn't contain a valid double value and when it returns true, thevaluevariable will hold it's value.Here is the example code: