Quantcast
Channel: Continue loop between classes after wrong input - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Steve for Continue loop between classes after wrong input

$
0
0

You could use the same pattern used by Int32.TryParse. Meaning you pass the number to be added as an out parameter and return a boolean false if the number is not valid

public static bool ReadIntegerConsole2(out int number)
{
    int input;
    bool ok = true;

    number = 0;
    if (int.TryParse(Console.ReadLine(), out input))
        number = input;
    else
    {
        ok = false;
        Console.WriteLine("Wrong input. Please try again: ");
    }
    return ok;
}

Now in the calling code you can control the loop knowing the result of the call to ReadInteger2

private void SumNumbers() 
{
    int index;
    int num = 0;
    for (index = 1; index <= numOfInput; index++) 
    {
        Console.Write("Please give the value no. " + index + " (whole number):");
        if(Input.ReadIntegerConsole2(out num))
            sum += num;
        else 
            // Decrement the counter to avoid skipping an input
            index--;
    }
}

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>