L
L
Ledington2021-09-06 10:51:54
C++ / C#
Ledington, 2021-09-06 10:51:54

How to access a method?

I have a loop that repeats multiple times.
How can I make a method out of it? At the same time, so that it is called depending on the number of variables.
For example, on the variable a, b and c?

Console.WriteLine($"\na * x^2 + b * x + c = 0");

var a = string.Empty;
var b = string.Empty;
var c = string.Empty;

            while (true) //цикл обработки значения <a>
            {
                Console.Write($"\nВведите значение <a>: ");
                a = Console.ReadLine();
                bool a_number = int.TryParse(a, out int ai);

                if (a_number)
                    if (ai % 2 == 0)
                    {
                        Console.WriteLine($"Было введено число: {ai}");
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Некорректные данные. Попробуйте еще раз.");
                    }
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Foggy Finder, 2021-09-06
@Ledington

It's not clear what exactly you didn't get. The idea itself is correct - to put the common functionality into a method.
The only thing that could cause complexity is to make an additional restriction on the entered data. For example, you still need parity for parameter a . To do this, you can simply pass a filter:

static int ReadInt(Func<int, bool> filter)
{
    while (true)
    {
        var a = Console.ReadLine();
        bool a_number = int.TryParse(a, out int ai);

        if (a_number && filter(ai))
        {
            return ai;
        }
        else
        {
            Console.WriteLine("Некорректные данные. Попробуйте еще раз.");
        }
    }
}

and an example call
Console.Write($"\nВведите четное значение <a>: ");
var a = ReadInt(a => a % 2 == 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question