Open uwuhazelnut opened 1 year ago
Done:
public static int getUserOption(int optionAmount)
{
int option; // The option chosen by the user is stored in the option variable
bool optionCheck = int.TryParse(Console.ReadLine(), out option); // TryParse returns a false boolean if the user enters invalid input which makes error handling easier
// Set the check boolean to false if the user enters an option that doesn't exist:
if (option > optionAmount || option < 0)
{
optionCheck = false;
}
// Get new user input if previous input was invalid:
while (optionCheck == false)
{
Console.WriteLine("Ungültige Option, nochmal versuchen:");
optionCheck = int.TryParse(Console.ReadLine(), out option);
if (option > optionAmount || option < 0)
{
optionCheck = false;
}
}
return option;
}
Optimisation:
public static int getUserOption(int optionAmount)
{
int option; // The option chosen by the user is stored in the option variable
// Repeat user input request until valid input has been entered:
while (true)
{
bool optionCheck = int.TryParse(Console.ReadLine(), out option); // TryParse returns a false boolean if the user enters invalid input which makes error handling easier
if (option >= 0 && option <= optionAmount && optionCheck)
{
break;
}
Console.WriteLine("Ungültige Option, nochmal versuchen:");
}
return option;
}
I want to move the following code to a function so it can be used multiple times without flooding the code: