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)); }
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; } } } }
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); }
public void Predict() { CH.WriteSeparator(); Console.WriteLine("Please choice prediction interval: "); var choiceResult = CH.GetChoiceFromUser <Period>(true); CH.ClearLine(2); Console.WriteLine(Predict(choiceResult)); }
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(); }
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"); } }
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(); }
private static void Main(string[] args) { CH.SetConsoleColor(); CH.SetConsoleOutputEncoding(); TaskOne(); CH.WriteSeparator(); CH.WriteSeparator(); TaskTwo(); CH.WriteSeparator(); CH.WriteSeparator(); TaskThree(); Console.ReadKey(); }
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(); }
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); }
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); } }
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); }); }
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(); }
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(); }
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); } }