dustin
dustin

Reputation: 49

Restart the codeblock with a while-loop

Problem: I would like to restart my codeblock after the error message.

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");

if (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

Upvotes: 0

Views: 108

Answers (3)

adjan
adjan

Reputation: 13674

Use a do ... while loop:

bool error;
do
{
    Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
    error = !double.TryParse(Console.ReadLine(), out zahl1); 
    if (error)
        Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");
} while(error);

Upvotes: 2

Ron Beyer
Ron Beyer

Reputation: 11273

It would be very simple:

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

    Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
}

You need to make sure to prompt the user again, otherwise they will not know that they need to enter another number.

Upvotes: 1

Samuel Vidal
Samuel Vidal

Reputation: 943

You can just change your if into a while:

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
while (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

Upvotes: 1

Related Questions