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

Answer by Peter Duniho for Continue loop between classes after wrong input

$
0
0

There are many possible ways to accomplish your goal. But it seems to me one of the most obvious is to follow the example set by int.TryParse(), which you are already using. Change your ReadIntegerConsole2() method to work the same way:

public static bool TryReadIntegerConsole2(out int input)
{
    if (int.TryParse(Console.ReadLine(), out input))
        return true;

    Console.WriteLine("Wrong input. Please try again: ");
    return false;
}

Then use it in your loop like this:

private void SumNumbers()
{
    int index;
    int num = 0;
    for (index = 1; index <= numOfInput; index++) // Loop that asks the quesion d
    {
        do
        {
            Console.Write("Please give the value no. " + index + " (whole number):");
        } while (!Input.TryReadIntegerConsole2(out num));
        sum += num;
    }
}

Viewing all articles
Browse latest Browse all 4

Trending Articles



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