
Joseph J. answered 06/08/21
Senior .NET Software Engineer with 20+ Years of Experience
For a console app it would go something like this:
// Create an array to hold jumps, this does not need to be an array,
// it could be separate float variable or a list of floats.
// Using a list of floats would allows for as many entry's as you wish.
// (The for loop would need to become a while)
float[] jumps = new float[4];
// Prompt the users to select the measurement units
Console.WriteLine("Select the type of units your jumps are measured in.");
Console.WriteLine("(F) - Feet");
Console.WriteLine("(M) - Meters");
char unit='x';
string strUnits = "Feet";
// Use the while loop to capture, validate an assign the measurement string.
// This code could be refactor to be less verbose, but I did this way for
// better understanding of the concept
while (unit == 'x')
{
//Capture the users input using a single key stroke
//Using ReadLine() would allow for more opportunity of invalid data entry
unit = char.ToUpper(Console.ReadKey(true).KeyChar);
// Validate the entry against valid values
if (unit != 'M' && unit != 'F')
{
// if invalid data entered reset the unit variable and continue the loop
unit = 'x';
continue;
}
// if a valid entry was supplied update the strUnit variable for displaying
switch (unit)
{
case 'F':
strUnits = "Feet";
break;
case 'M' :
strUnits = "Meters";
break;
}
}
// Use the for loop to capture the number of jumps based on the arrays length
// If you convert this to a list of floats you will need to use the while loop instead
for(int i = 0; i < jumps.Length; i++)
{
while (jumps[i] == 0.00f){
//Prompt the user for the current jumps value
Console.WriteLine($"Enter the lentgh of jump #{i}");
// Use floats tryparse extension method to validate the entry is a valid numeric float
if (!float.TryParse(Console.ReadLine(), out jumps[i]))
{
// If the tryparse fails alert the user and continue the loop from the top
Console.WriteLine($"Invlaid entry! Enter a valid (positive) numeric value for jump #{i+1}");
continue;
}
// If the tryparse passes but the value is not positive, alert the user,
// reset the index value of the jump array to zero and continue the loop from the top
if (jumps[i] < 0.00f){
Console.WriteLine($"Invlaid entry! Enter a valid (positive) numeric value for jump #{i+1}");
jumps[i] = 0.00f;
}
}
}
// Once all jumps have been entered run the arrays average extension method to calculate the average
// You can also manually calculate if you desire
float averageJump = jumps.Average();
// Print the average to the user.
// If you are creating a forms type application
// supply the averageJump variable to the display control.
Console.WriteLine($"You averaged {averageJump} {strUnits} per jump");