uwuhazelnut / DateiRenamer

0 stars 0 forks source link

DateiRenamer - move user option code to a function for reusability #5

Open uwuhazelnut opened 1 year ago

uwuhazelnut commented 1 year ago

I want to move the following code to a function so it can be used multiple times without flooding the code:

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 > 1)
{
    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 > 1)
    {
        optionCheck = false;
    }
}
uwuhazelnut commented 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;
}
uwuhazelnut commented 1 year ago

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;
}