Exemple #1
0
        public void CheckLections()
        {
            foreach (var lectionPair in Lections)
            {
                var lection = lectionPair.Key;

                CH.WriteSeparator();

                Console.WriteLine(LectionTemplateString, lection.Type, lection.Theme, lection.Classroom);
                CH.WriteSeparator();

                var humansOnLection = lectionPair.Value;

                foreach (var human in humansOnLection)
                {
                    switch (human)
                    {
                    case Student student:
                        student.Learn(lection.Type);
                        break;

                    case Lecturrer lecturrer:
                        lecturrer.Work(lection.Type);
                        break;

                    default:
                        Console.Write($"{human} is eating. ");
                        human.Eat();
                        break;
                    }
                }
            }
        }
Exemple #2
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            var rand = new Random((int)DateTime.Now.Ticks);

            ;
            var field = new Field(rand.Next(10, 20), rand.Next(10, 20));

            while (true)
            {
                switch (CH.GetChoiceFromUser(new[] { "Generate new animals", "To next step" }, true, true).ChoisedIndex)
                {
                case 0:
                    field.GenerateNewAnimals(rand.Next(5, 20), rand.Next(2, 5));
                    break;

                case 1:
                    field.NextStep();
                    break;

                case -1:
                    return;
                }
            }
        }
Exemple #3
0
        private static Tuple <string, decimal> GetNewPurchaseInfo()
        {
            bool isInputValid;

            string  purchaseName;
            decimal purchasePrice;

            do
            {
                CH.WriteSeparator();

                purchaseName = CH.GetStringFromConsole("Please input the purchase name [Butter/Wine/Caviar/ e.t.c.]");
                var purchasePriseStr =
                    CH.GetStringFromConsole($"Please input the purchase price [{0.5m:C}/{9.99m:C}/ e.t.c.]");

                var isValidPurchaseName  = !string.IsNullOrWhiteSpace(purchaseName);
                var isValidPurchasePrice = decimal.TryParse(purchasePriseStr, out purchasePrice);

                isInputValid = isValidPurchaseName && isValidPurchasePrice;


                if (!isInputValid)
                {
                    Console.WriteLine("Incorrect input. Try again.");
                }
            } while (!isInputValid);

            return(new Tuple <string, decimal>(purchaseName, purchasePrice));
        }
Exemple #4
0
        private static void WritePurchasesListToConsole(Dictionary <string, decimal> purchasesList, bool isPriceVisible,
                                                        int filterDirection, decimal filterValue)
        {
            const string captionStr          = "Shopping List";
            const string filtrStr            = "Filter applied to the list. Items with a price {0} than {1,25:C} are displayed.";
            const string listStrWithPrice    = "|{0,25}|{1,15:C}|";
            const string listStrWithoutPrice = "|{0,25}|";


            Console.WriteLine(captionStr);
            CH.WriteSeparator();

            if (filterDirection != 0)
            {
                Console.WriteLine(filtrStr, filterDirection == 2 ? "higher" : "lower", filterValue);
                CH.WriteSeparator();
            }

            Console.WriteLine(isPriceVisible ? listStrWithPrice : listStrWithoutPrice, "Purchase name", "Price");

            foreach (var keyValuePair in purchasesList)
            {
                switch (filterDirection)
                {
                case 1 when keyValuePair.Value > filterValue:
                case 2 when keyValuePair.Value < filterValue:
                    continue;
                }

                Console.WriteLine(isPriceVisible ? listStrWithPrice : listStrWithoutPrice, keyValuePair.Key,
                                  keyValuePair.Value);
            }

            Console.WriteLine(Environment.NewLine);
        }
Exemple #5
0
        public void Predict()
        {
            CH.WriteSeparator();
            Console.WriteLine("Please choice prediction interval: ");
            var choiceResult = CH.GetChoiceFromUser <Period>(true);

            CH.ClearLine(2);
            Console.WriteLine(Predict(choiceResult));
        }
Exemple #6
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            const string inputMsg        = "Введитк натуральное число (n>0) : ";
            const string noPrimeMsg      = "Нет простых чисел в выбранном диапазоне";
            const string invalidInputMsg = "Введены неверные значения...";
            const string outMsg          = "{0,10}";

            var inputString = CH.GetStringFromConsole(inputMsg);

            if (!uint.TryParse(inputString, out var n))
            {
                Console.WriteLine(invalidInputMsg);
                Console.ReadKey();
                return;
            }

            CH.WriteSeparator();

            if (n == 1)
            {
                Console.WriteLine(noPrimeMsg);
            }
            else if (n >= 2)
            {
                Console.Write(outMsg, 2);


                for (uint number = 2; number <= n; number++)
                {
                    var isPrime = false;

                    for (uint oldNumber = 2; oldNumber <= Math.Ceiling(Math.Sqrt(number)); ++oldNumber)
                    {
                        if (number % oldNumber != 0)
                        {
                            isPrime = true;
                            break;
                        }
                    }

                    if (isPrime)
                    {
                        Console.Write(outMsg, number);
                    }
                }
            }

            Console.WriteLine();
            CH.WriteSeparator();

            //exit
            Console.ReadKey();
        }
Exemple #7
0
        private static void Variant_2_New()
        {
            const string digitsTemolate = "##";
            const int    digitsOffset   = 48;

            const int offsetLeft = 20;
            const int offsetTop  = 20;

            var timeString =
                $"Минское время {digitsTemolate}:{digitsTemolate}:{digitsTemolate}. Говорят и показывают все телестанции страны... "; //выводиая строка

            var buffer       = timeString.ToCharArray();
            var hoursIndex   = timeString.IndexOf(digitsTemolate);
            var munitsIndex  = timeString.IndexOf(digitsTemolate, hoursIndex + 1);
            var secondsIndex = timeString.IndexOf(digitsTemolate, munitsIndex + 1);

            //Выводим рамку
            CH.DrawRect(new Position(offsetLeft - 1, offsetTop - 1), new Size(LineSize, 1));

            CH.SetConsoleColor(ConsoleColor.DarkYellow); //Цвет текста

            var currentPosition = 0;

            while (true)
            {
                //'Обновляем' время в буфере, если оно изменилось
                var newTime = DateTime.Now;

                buffer[hoursIndex]     = newTime.Hour < 10 ? '0' : (char)(newTime.Hour / 10 + digitsOffset);
                buffer[hoursIndex + 1] = (char)(newTime.Hour % 10 + digitsOffset);

                buffer[munitsIndex]     = newTime.Minute < 10 ? '0' : (char)(newTime.Minute / 10 + digitsOffset);
                buffer[munitsIndex + 1] = (char)(newTime.Minute % 10 + digitsOffset);

                buffer[secondsIndex]     = newTime.Second < 10 ? '0' : (char)(newTime.Second / 10 + digitsOffset);
                buffer[secondsIndex + 1] = (char)(newTime.Second % 10 + digitsOffset);


                var charsToStringEnd = buffer.Length - currentPosition; // Находим остаток до конца буфера

                Console.SetCursorPosition(offsetLeft, offsetTop);       // прыгаем в начало бегущей стоки

                if (charsToStringEnd >= LineSize)                       //если хватает то виыводим так
                {
                    Console.Write(buffer, currentPosition, LineSize);
                }
                else // если нет, то добисываем с начала буфера
                {
                    Console.Write(buffer, currentPosition, charsToStringEnd);
                    Console.Write(buffer, 0, LineSize - charsToStringEnd);
                }

                Thread.Sleep(SleepInterval);                         //Поток спит
                currentPosition = ++currentPosition % buffer.Length; //Идём на следующий символ
            }
        }
Exemple #8
0
        private const int SleepInterval = 150; //Интервал обновления

        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            Console.CursorVisible = false;

            //Varian_1_Old();
            Variant_2_New();
        }
Exemple #9
0
 private void WriteFieldStatus()
 {
     CH.WriteSeparator();
     Console.WriteLine(
         $"On field:\n -Grass count {_grassCount}\n -Rabbits count: {_rabbits.Count}\n -Tigers count: {_tigers.Count}");
     if (_rabbits.Count == 0 && _tigers.Count == 0)
     {
         Console.WriteLine("\tAll dead");
     }
 }
Exemple #10
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            var students = new List <Student>
            {
                new Student("Abdul", "Student 1", "Departament 1", 1, "G1"),
                new Student("Vdul", "Student 2", "Departament -2", 1, "G2"),
                new Student("Opozdal", "Student 3", "Departament 3", 1, "G3"),
                new Student("Umni", "Student 4", "Departament 666", 1, "G666"),
                new Student("Knyzz", "From last table", "Departament 666", 1, "G666") //4
            };

            var lecturers = new List <Lecturer>
            {
                new Lecturer("Uchit", " Chemuto", "Gdeto", "O chomto"),
                new Lecturer("NE Uchit", " Chemuto", "TamTO", "Ni o chom")
            };

            var heads = new List <HeadLecturrer>
            {
                new HeadLecturrer("Zloy", "Dulahan", "Hell", 666)
            };

            var univarcity = new University();

            foreach (var student in students)
            {
                univarcity.UnivrsityHumans.Add(student);
            }

            foreach (var lecturer in lecturers)
            {
                univarcity.UnivrsityHumans.Add(lecturer);
            }

            foreach (var head in heads)
            {
                univarcity.UnivrsityHumans.Add(head);
            }

            CH.WriteSeparator();

            univarcity.UnivrsityHumans.Add(students[4]); //there must be error in log

            CH.WriteSeparator();
            CH.WriteSeparator();

            univarcity.UniversityWork();

            Console.ReadKey();
        }
Exemple #11
0
        private static void Main(string[] args)
        {
            CH.SetConsoleColor();
            CH.SetConsoleOutputEncoding();

            var newStudents = new List <Student> // TODO надо закоментить ненужные
            {
                new Student(),
                new Student {
                    LastName = null
                },
                new Student {
                    FirstName = null
                },
                null
            };

            var group    = new StudentGroup(new List <Student>(), new ConsoleLogger());
            var newGroup = new StudentGroup(new List <Student>(newStudents), new ConsoleLogger());


            try
            {
                foreach (var student in newStudents)
                {
                    group.AddStudent(student);
                }
            }
            catch (InvalidStudentInput e)
            {
                Console.WriteLine(e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine(e.InnerException.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }


            try
            {
                group.AddStudentsFromGroup(newGroup);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadKey();
        }
Exemple #12
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            var songs = new List <Song>
            {
                new Song("Super Band", "Super Song"),
                new Song(title: "Super Song"),
                new Song("Super Band"),
                new Song("Giper Band", "Awful Song"),
                new Song("Super Band", "Super Song"),
                new Song("Just Band", "Isn't Song"),
                new Song("Band of justice", "Super Song"),
                new Song(),
                new Song("My", "First SOng", 500, 300),
                new Song("My", "Second song", 1500, 700)
            };

            var myFirstAlbum = new Album("My First Album"); // or new Album();

            foreach (var song in songs)
            {
                myFirstAlbum.AddSong(song);
            }

            var player = new Player();

            var rand = new Random(DateTime.Now.Second);

            Console.Write($"We are ready to play All album ({myFirstAlbum.Songs.Count})");
            Console.ReadKey();
            player.PlayAlbum(myFirstAlbum);

            var from = rand.Next(0, myFirstAlbum.Songs.Count);

            Console.WriteLine(Environment.NewLine);
            Console.Write($"We are ready to play from song #{from + 1} to end of album");
            Console.ReadKey();
            player.PlayAlbum(myFirstAlbum, from);

            from = rand.Next(0, myFirstAlbum.Songs.Count);
            var to = rand.Next(from, myFirstAlbum.Songs.Count);

            Console.WriteLine(Environment.NewLine);
            Console.Write($"We are ready to play album from song #{from + 1} to #{to + 1} song");
            Console.ReadKey();
            player.PlayAlbum(myFirstAlbum, from, to);

            Console.WriteLine("That is all. Goodbye");
            Console.ReadKey();
        }
Exemple #13
0
        private static void Main(string[] args)
        {
            CH.SetConsoleColor();
            CH.SetConsoleOutputEncoding();

            TaskOne();
            CH.WriteSeparator();
            CH.WriteSeparator();
            TaskTwo();
            CH.WriteSeparator();
            CH.WriteSeparator();
            TaskThree();

            Console.ReadKey();
        }
Exemple #14
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            //output caption
            CH.WriteSeparator();
            Console.WriteLine("\t\t\t\t\t\t- Sphere Calculator -");
            CH.WriteSeparator();
            Console.WriteLine("\t\t\t\t\t\t-= Basic Formulas =-");
            Console.WriteLine("\t\t\t\t\tVolume=(4/3)\u03C0R\u00B3 m\u00B3 & Area = 4\u03C0R\u00B2 m\u00B2");

            //input radius of sphere
            CH.WriteSeparator();
            var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            double sphereRadius;
            string sphereRadiusString;

            do
            {
                sphereRadiusString = CH.GetStringFromConsole(
                    $"Please enter the radius (R) of your sphere in meters (m) [you must separate of number parts with \"{separator}\" char]");
            } while (!double.TryParse(sphereRadiusString, out sphereRadius));


            //convertation & calculations

            var sphereV = 4.0 / 3.0 * Math.PI * Math.Pow(sphereRadius, 3.0);
            var sphereA = 4.0 * Math.PI * Math.Pow(sphereRadius, 2.0);

            //output results
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            CH.WriteSeparator();

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(
                "\tVolume=(4/3)\u03C0R\u00B3={0:0.###} m\u00B3{1}\tArea=(4/3)\u03C0R\u00B3={2:0.###} m\u00B2", sphereV,
                Environment.NewLine, sphereA);

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            CH.WriteSeparator();
            Console.WriteLine(
                $"\tThank you for using our program, we hope it helped you :D {Environment.NewLine}\tGoodbye!");

            //exit
            Console.ReadKey();
        }
Exemple #15
0
        private static decimal GetPriceFilterValue()
        {
            bool    isInputValid;
            decimal priceFilterValue;

            do
            {
                CH.WriteSeparator();

                var priceFilterValueStr = CH.GetStringFromConsole($"filter value [{0.5m:C}/{9.99m:C}]");

                isInputValid = decimal.TryParse(priceFilterValueStr, out priceFilterValue);
            } while (!isInputValid);

            return(priceFilterValue);
        }
Exemple #16
0
        TaskOne()
        {
            // TODO Задача 1 Делегаты и методы

            /*
             * 1. Объявить делегат для работы с выборками.
             * 2. Создать метод, в классе каталог, позволяющий делать выборки из каталога.
             * 3. Создать класс BookSorter и объявить в нём методы необходимые для
             *  выполнения задач по сортировке книг
             * 3. Вывести в консоль книги написанные до 85ого года. Передав статический метод и BookSorter-a
             * 4. Вывести книги написаны в названии которых есть слово "мир"
             */
            var catalog = new Catalog
            {
                Books = new List <Book>
                {
                    new Book {
                        Title = "Book 1 About eat", DoP = new DateTime(1984, 1, 1)
                    },
                    new Book {
                        Title = "Book 2 About our little world", DoP = new DateTime(1983, 1, 1)
                    },
                    new Book {
                        Title = "Book 3 About cars", DoP = new DateTime(1988, 1, 1)
                    },
                    new Book {
                        Title = "Book 4 Around the world in One tick", DoP = new DateTime(1999, 1, 1)
                    }
                }
            };

            var booksBefore85Year = catalog.SelectBooks(BookSorter.IsBookBefore85Year);

            foreach (var book in booksBefore85Year)
            {
                Console.WriteLine(book);
            }

            CH.WriteSeparator();

            var booksWithWordWorld = catalog.SelectBooks(BookSorter.IsContainsWordWoldInTitle);

            foreach (var book in booksWithWordWorld)
            {
                Console.WriteLine(book);
            }
        }
Exemple #17
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            switch (CH.GetChoiceFromUser(new[] { "Attachment", "Presentation" }, true, true).ChoisedIndex)
            {
            case 0:
                new Predictor().Predict();
                break;

            case 1:
                Console.WriteLine("Ha-ha there is nothing. See source files in folder \"Presentation\"");
                break;
            }

            Console.ReadKey();
        }
Exemple #18
0
        private static void TaskTwo()
        {
            // TODO Задача 2 Делегаты и анонимные методы и/или лямбда выражения

            /*
             * 1. Объявить делегаты для работы со студентами
             * 2. Создать метод, в классе группа, позволяющий сортировать студентов.
             * 3. Создать метод, в классе группа, предоставляющий возможность выполнить действие
             *  с приватной коллекцией студентов.
             * 4. Используя метод из пункта 2, отсортировать студентов по средней оценке
             * 5. Используя метод из пункта 3, всем студентам с оценкой от 4 до 6 добавить 1 балл.
             */

            const string studentTemplate = "{0} {1} - Avg mark: {2}";

            var group = new Group(new[]
            {
                new Student(),
                new Student(),
                new Student(),
                new Student(),
                new Student(),
                new Student(),
                new Student()
            });

            group.Sort((student1, student2) => (int)(student1.AvgMark - student2.AvgMark));

            group.DoSomethingWith(
                student => true,
                student => Console.WriteLine(studentTemplate, student.FirstName, student.LastName, student.AvgMark));

            CH.WriteSeparator();

            group.DoSomethingWith(
                student => student.AvgMark >= 4 && student.AvgMark <= 6,
                student =>
            {
                Console.Write(studentTemplate, student.FirstName, student.LastName, student.AvgMark);
                student.AddToMark(1);
                Console.Write(" -> ");
                Console.WriteLine(studentTemplate, student.FirstName, student.LastName, student.AvgMark);
            });
        }
Exemple #19
0
        private static void Main(string[] args)
        {
            CH.SetConsoleColor();
            CH.SetConsoleOutputEncoding();

            var tracks = new List <Track>
            {
                new Track("SomeFilePath0", "Track #0", "Some Band", new TimeSpan(1, 0, 0, 0)),
                new Track("SomeFilePath0", "Track #1", "Some Band", new TimeSpan(0, 1, 0, 0)),
                new Track("SomeFilePath0", "Track #2", "Some Band", new TimeSpan(0, 0, 1, 0)),
                new Track("SomeFilePath0", "Track #3", "Some Band", new TimeSpan(0, 0, 0, 1))
            };
            var labum = new Album("Album which will be serialized", new LinkedList <Track>(tracks));

            IAlbumSerializer serializer = new BinaryAlbumSerializer(MusicLibraryDir);

            Console.WriteLine("Saving into file:");

            var filePath = serializer.SaveToFile(labum);

            Console.WriteLine($"Labum was successfully saved. FilePath: {filePath}");
            CH.WriteSeparator();
            Console.ReadKey();

            Console.WriteLine("Loading from file:");

            var labumFromFile = serializer.LoadFromFile(filePath);

            CheckAlbum(labumFromFile);
            CH.WriteSeparator();
            Console.ReadKey();

            Console.WriteLine("Loading from BinaryArray:");

            var buffer = File.ReadAllBytes(filePath);
            var labumFromBinaryArray = serializer.LoadFromBinaryArray(buffer);

            CheckAlbum(labumFromBinaryArray);
            CH.WriteSeparator();
            Console.ReadKey();
        }
Exemple #20
0
        private static void Main(string[] args)
        {
            CH.SetConsoleColor();
            CH.SetConsoleOutputEncoding();

            var op         = new NewsOperator();
            var subscriber = new NewsSubscriber(NewsCategory.Sport);

            var newNews = new News
            {
                Category         = NewsCategory.Sport | NewsCategory.Events,
                Title            = SomeNewsTitleString,
                ShortDescription = SomeNewsDescriptionString,
                Content          = SomeNewsContentString
            };

            op.Subscribe(subscriber);

            op.AddNews(newNews);

            Console.ReadKey();
        }
Exemple #21
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            //TODO 1.Создать консольное приложения для работы со списком покупок.
            //     2.Добавить возможность добавления покупки «называние» «цена»
            //     3.Добавить возможность «узнать цену товара»
            //     4.Добавить возможность «вывести товары дороже чем»

            var purchasesList = new Dictionary <string, decimal>();

            var filterValue     = 0m;
            var filterDirection = 0;
            var isPriceVisible  = false;

            var selectedMenuIndex = -1;

            string[] menuOptions =
            {
                "Add purchase",     //0
                "Set price filter", //1
                "Show/Hide prices", //2
                "Exit"              //3
            };

            InitializePurchasesListByDefault(purchasesList);

            while (true)
            {
                Console.Clear();

                WritePurchasesListToConsole(purchasesList, isPriceVisible, filterDirection, filterValue);

                if (selectedMenuIndex == -1) // Show main menu
                {
                    Console.WriteLine("Options:");
                    selectedMenuIndex = CH.GetChoiceFromUser(menuOptions).ChoisedIndex;
                }
                else
                {
                    switch (selectedMenuIndex)
                    {
                    case 0:
                        var newPurchase = GetNewPurchaseInfo();

                        if (purchasesList.ContainsKey(newPurchase.Item1))
                        {
                            Console.WriteLine("Purchase already exist in list or invalid");
                        }
                        else
                        {
                            purchasesList.Add(newPurchase.Item1, newPurchase.Item2);
                            Console.WriteLine("Purchase was added to list");
                        }

                        break;

                    case 1:
                        string[] options =
                        {
                            "No",                                                         //0
                            "Yes i do, i want to see purchases with price LOWER than...", //1
                            "Yes i do, i want to see purchases with price HIGHER than..." //2
                        };

                        Console.WriteLine("Do you want to filter list?");
                        filterDirection = CH.GetChoiceFromUser(options).ChoisedIndex;

                        if (filterDirection != 0)
                        {
                            filterValue = GetPriceFilterValue();
                        }
                        break;

                    case 2:
                        Console.WriteLine("Do you want to see prices in the purchases list?");
                        isPriceVisible = CH.GetChoiceFromUser(new[] { "No", "Yes" }).ChoisedIndex != 0;
                        break;

                    case 3:
                        return;
                    }

                    selectedMenuIndex = -1;
                }
            }
        }
Exemple #22
0
        private static void Main(string[] args)
        {
            CH.SetConsoleOutputEncoding();
            CH.SetConsoleColor();

            const int numberOfPeriods = 12;

            const string inputMsg1       = "Введите cумму кредитования, \u00A4";
            const string inputMsg2       = "Введите ставку кредитования, % [1 - 100% как 15,5% ]";
            const string paymentTypeMsg  = "Выберите вид платежа:";
            const string paymentTypeMsg1 =
                "1 - аннуитетный платеж - это равный по сумме ежемесячный платеж по кредиту;";
            const string paymentTypeMsg2 =
                "2 - дифференцированный платеж -  это ежемесячный платеж, уменьшающийся к концу срока кредитования.";
            const string invalidInputMsg = "Введены неверные значения...";
            const string tableLineMsg    =
                " | {0,6} | {1,13:0.##}\u00A4 | {2,13:0.##}\u00A4 | {3,13:0.##}\u00A4 | {4,13:0.##}\u00A4 |";
            const string tableFooterLineMsg = " | Итого: | {0,30:0.##}\u00A4 | {1,13:0.##}\u00A4 | {2,13:0.##}\u00A4 |";

            CH.WriteSeparator();

            //input
            var creditAmountString = CH.GetStringFromConsole(inputMsg1);
            var creditRateString   = CH.GetStringFromConsole(inputMsg2);

            CH.WriteSeparator();

            var amountIsInvalid = !decimal.TryParse(creditAmountString, out var originalCreditAmount);
            var rateIsInvalid   = !double.TryParse(creditRateString, out var creditInterestRate);


            if (amountIsInvalid || rateIsInvalid || originalCreditAmount <= 1 || creditInterestRate < 1 ||
                creditInterestRate > 100)
            {
                Console.WriteLine(invalidInputMsg);
                Console.ReadKey();
                return;
            }


            Console.WriteLine(paymentTypeMsg);
            var choosedStringIndex = CH.GetChoiceFromUser(new[] { paymentTypeMsg1, paymentTypeMsg2 }, true).ChoisedIndex;

            CH.WriteSeparator();


            var sumOfInterestCharges = 0m;
            var sumOfPayments        = 0m;
            var debt = originalCreditAmount;

            creditInterestRate *= 0.01;

            //Table
            Console.WriteLine(tableLineMsg, "Период", "Задолженность", "Начисленные %",
                              "Основной долг", "Сумма платежа");

            if (choosedStringIndex == 0) //аннуитетный платеж
            {
                var monthlyCreditInterestRate = creditInterestRate / 12;
                var amountOfPayment           = originalCreditAmount *
                                                (decimal)(monthlyCreditInterestRate +
                                                          monthlyCreditInterestRate /
                                                          (Math.Pow(1 + monthlyCreditInterestRate, 12d) - 1d));

                for (var period = 1; period <= 12; period++)
                {
                    var interestCharges   = debt * (decimal)monthlyCreditInterestRate;
                    var repaymentOfCredit = amountOfPayment - interestCharges;

                    Console.WriteLine(tableLineMsg, period, debt, interestCharges,
                                      repaymentOfCredit, amountOfPayment);

                    debt -= repaymentOfCredit;

                    sumOfInterestCharges += interestCharges;
                    sumOfPayments        += amountOfPayment;
                }
            }
            else //дифференцированный платеж
            {
                var repaymentOfCredit = originalCreditAmount / numberOfPeriods;
                var currentYear       = DateTime.Today.Year;

                for (var period = 1; period <= 12; period++)
                {
                    var interestCharges =
                        debt * (decimal)(creditInterestRate * DateTime.DaysInMonth(currentYear, period) / 365d);
                    var amountOfPayment = repaymentOfCredit + interestCharges;

                    Console.WriteLine(tableLineMsg, period, debt, interestCharges,
                                      repaymentOfCredit, amountOfPayment);

                    debt -= repaymentOfCredit;

                    sumOfInterestCharges += interestCharges;
                    sumOfPayments        += amountOfPayment;
                }
            }


            CH.WriteSeparator();
            Console.WriteLine(tableFooterLineMsg, sumOfInterestCharges, originalCreditAmount, sumOfPayments);
            CH.WriteSeparator();

            //Exit
            Console.ReadKey();
        }
Exemple #23
0
        private static void TaskThree()
        {
            // TODO Задача 3* Func, Action + =>
            // В задаче нельзя объявлять делегаты

            /*
             * 1. Создать методы расширения для класса CarPark:
             *  а. Производит выборку из внутренней коллекции используя передаваемую функцию
             *  б. Производит сортировку внутренней коллекции используя передаваемую функцию
             * 2. Создать внутреннее свойство в классе CarPark для хранение действия.
             * 3. Вызывать это действие при добавлении новой машины в парк:
             *   => Как вариант выводить в консоль информацию о машине
             *   Console: Toyota RAV4 was added to the park. It costs ... $.
             */

            const string carTempolate = " {0} - {1} Price: {2}";

            var group = new CarPark
            {
                AddNewCarAction = car =>
                {
                    Console.WriteLine($"- {car.Brand} {car.Model} was added to the park. It costs {car.Price} $");
                },
                Cars = new List <Car>
                {
                    new FuelCar
                    {
                        Brand        = "Brand 1",
                        Model        = "Model A",
                        Price        = 12000m,
                        ReleasedYead = 1990,
                        TankSize     = 100
                    },
                    new FuelCar
                    {
                        Brand        = "Brand 2",
                        Model        = "Model A",
                        Price        = 1200m,
                        ReleasedYead = 1990,
                        TankSize     = 100
                    },
                    new FuelCar
                    {
                        Brand        = "Brand 3",
                        Model        = "Model A",
                        Price        = 15000m,
                        ReleasedYead = 1990,
                        TankSize     = 100
                    },
                    new FuelCar
                    {
                        Brand        = "Brand 1",
                        Model        = "Model A",
                        Price        = 23400m,
                        ReleasedYead = 1990,
                        TankSize     = 100
                    }
                }
            };

            //Before sort
            foreach (var car in group.Cars)
            {
                Console.WriteLine(carTempolate, car.Brand, car.Model, car.Price);
            }

            CH.WriteSeparator();

            group.SortCars((car1, car2) => (int)(car1.Price - car2.Price));
            //After sort
            foreach (var car in group.Cars)
            {
                Console.WriteLine(carTempolate, car.Brand, car.Model, car.Price);
            }

            CH.WriteSeparator();

            var brand1Cars = group.SelectCars(car => car.Brand == "Brand 1");

            //Selected
            foreach (var car in brand1Cars)
            {
                Console.WriteLine(carTempolate, car.Brand, car.Model, car.Price);
            }
        }