dustin
dustin

Reputation: 49

Restart the while loop after the error message in the output

Problem: How can I restart the following codeblock? My idea is if you enter a character that will return an error message. What is the condition for the loop?

string r_operation;
Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
r_operation = Console.ReadLine();
-------------

while (?r_operation = Console.ReadLine())
{
Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
}

Upvotes: 2

Views: 239

Answers (1)

Rufus L
Rufus L

Reputation: 37060

You can convert your existing code to use the int.TryParse method, which returns a bool indicating if the input string is a valid number (and sets an out parameter to the converted value):

Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
string r_operation = Console.ReadLine();
int result = 0;

while (!int.TryParse(r_operation, out result))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
    Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
    r_operation = Console.ReadLine();
}

// When we exit the while loop, we know that 'r_operation' is a number, 
// and it's value is stored as an integer in 'result'

Another way to do this is to encapsulate the process of getting a strongly-typed number from the user into a method. Here's one I use:

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}

With these helper methods, your code can be reduced to:

int operation = GetIntFromUser("\tBitte geben Sie ihre Rechenoperation ein: ");

And if you wanted to add some additional constraints, the helper method also takes in a validator function (which takes an int and returns a bool indicating whether or not the int is valid). So if you wanted to restrict the numbers to be from 1 to 5, you could do something like:

var result = GetIntFromUser("Enter a number from 1 to 5: ", i => i > 0 && i < 6);

Upvotes: 2

Related Questions