Jakub Stanek
Jakub Stanek

Reputation: 45

C# how to return to previous statement

Hello im wondering how to return to previous statement in C#

For example i want to show user readline again when he filled it wrong and when he will do it right it will show him the next line of code/statement(in this exam. Console.WriteLine("Hi"))

How could i do it?

int num;
string prvnicislo;
prvnicislo = Console.ReadLine();

while (true)
{
    if (int.TryParse(prvnicislo, out num))
    {
        Convert.ToInt32(prvnicislo);
    }
    else
    {
        Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
        prvnicislo = Console.ReadLine();
    }
}
Console.WriteLine("Hi");

Upvotes: 0

Views: 2237

Answers (3)

YuvShap
YuvShap

Reputation: 3835

I think this will work:

 int num;
 string prvnicislo =  Console.ReadLine(); 
 while (!int.TryParse(prvnicislo, out num))
 {
     Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
     prvnicislo = Console.ReadLine();
 }
 Console.WriteLine("Hi");

Notice that there is not necessary to use Convert.ToInt32 because if the parsing has been succeed the TryParse method will assign the parsed int value to num.

Upvotes: 7

Amey Kamat
Amey Kamat

Reputation: 181

if this can be of any help

string prvnicislo = String.Empty;
bool isEntryWrong = true;

do
{
    Console.Write("Enter data: ");
    prvnicislo = Console.ReadLine();

    int num;
    if(int.TryParse(prvnicislo, out num))
    {
        isEntryWrong = false;
    }
    else
    {
        Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
    }
} while (isEntryWrong);

Console.WriteLine("Hi")

Upvotes: 0

Geeky
Geeky

Reputation: 7498

check the following code snippet

int num;
string prvnicislo;
prvnicislo = Console.ReadLine();

while (true)
{
    if (int.TryParse(prvnicislo, out num))
    {
        Convert.ToInt32(prvnicislo);
        break;
    }
    else
    {
        Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
        prvnicislo = Console.ReadLine();
    }
}

Console.WriteLine("Hi");

Hope this helps

Upvotes: 2

Related Questions