Advertisement
Pearlfromsu

s3l2

Sep 21st, 2022
1,126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 19.32 KB | None | 0 0
  1. 3
  2. Book
  3. Язык программирования C# 7 и платформы .NET и .NET Core
  4. ...Перевод с английского и редакция Ю.Н.Артеменко\nПо общим вопросам обращайтесь в издательство “Диалектика” по адресу:\ninform...
  5. 1330
  6. Russian
  7. Троелсен, Джепикс
  8. Библиотека ЯрГУ
  9. 100000
  10.  
  11. NewsPaper
  12. Известия
  13. ...Свежие новости: в Ярославле по адресу Союзная 144 студенты начали изучать ООП...
  14. 5
  15. Russian
  16. ЯрГУ
  17. 20
  18.  
  19. TextBook
  20. Математика
  21. ..Параграф 5. Простые и составные числа
  22. 95
  23. Russian
  24. Н. Я. Виленкин
  25. Кротов Сергей
  26. 200000
  27. 8
  28. Math
  29.  
  30.  
  31.  
  32. Book
  33. //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation
  34.  
  35. NewsPaper
  36. //string name, string contents, int pagesCount, Language lang, string publication, int printDate
  37.  
  38.  
  39. TextBook
  40. //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64. using System;
  65. using System.Collections.Generic;
  66. using System.Linq;
  67. using System.Text;
  68. using System.Threading.Tasks;
  69.  
  70. namespace s3l2 {
  71.     class NewsPaper : PrintedMatter {
  72.         string _publication; //издательство, выпустившее газету
  73.         int _printDate; //день выпуска газеты
  74.        
  75.         public NewsPaper(string name, string contents, int pagesCount, Language lang, string publication, int printDate) : base(name, contents, pagesCount, lang) {
  76.             Publication = publication;
  77.             PrintDate = printDate;
  78.         }
  79.         public NewsPaper() : base() {
  80.             Publication = "ЯрГУ";
  81.             PrintDate = DateTime.Now.Day;
  82.             //PrintDate = DateTime.Now;
  83.         }
  84.  
  85.         public override void PrintInfo() {
  86.             Console.WriteLine($"Информация о газете: {Name}");
  87.             Console.WriteLine($"Издательство: {Publication}");
  88.             base.PrintInfo();
  89.             Console.WriteLine($"День выпуска газеты: {PrintDate}");
  90.             //Console.WriteLine($"Дата издания газеты: {PrintDate.ToString("dd.MM.yyyy")}");
  91.         }
  92.  
  93.         public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
  94.             Console.WriteLine($"Содержание газеты “{Name}”:");
  95.             base.PrintContents();
  96.         }
  97.         public override void Open() { //переопределяем абстрактный метод open()
  98.             Console.WriteLine("Отображаем газету... ");
  99.             //...
  100.         }
  101.  
  102.  
  103.         public string Publication { //название печатного издания
  104.             get {
  105.                 return _publication;
  106.             }
  107.             private set {
  108.                 if (string.IsNullOrEmpty(value)) {
  109.                     this.LogError("Не задано название издательства газеты");
  110.                     _publication = "Unknown";
  111.                 } else
  112.                     _publication = value;
  113.             }
  114.         }
  115.         public int PrintDate { //тираж
  116.             get {
  117.                 return _printDate;
  118.             }
  119.             private set { //невозможно добавить или убрать страницы книги после печати
  120.                 if (value < 1 || value > 31) {
  121.                     this.LogError("Некорректный день выпуска газеты. Пересоздайте объект");
  122.                     _printDate = 1;
  123.                 } else
  124.                     _printDate = value;
  125.             }
  126.         }
  127.  
  128.         public override string ToString() {
  129.             return ($"Газета {Name} издательства {Publication}(Язык: {Lang}, {PagesCount} страниц, день выпуска: {PrintDate})");//HH:mm
  130.         }
  131.  
  132.         /*public DateTime PrintDate { //год(дата) издания
  133.             get {
  134.                 return _printDate;
  135.             }
  136.             private set {
  137.                 if (_printDate > DateTime.Now) { //нельзя напечатать издание в будущем
  138.                     Console.WriteLine("Газете установлена текущая дата");
  139.                     _printDate = DateTime.Now;
  140.                 } else
  141.                     _printDate = value;
  142.             }
  143.         }*/
  144.     }
  145. }
  146.  
  147.  
  148.  
  149.  
  150.  
  151.  
  152.  
  153.  
  154. using System;
  155. using System.Collections.Generic;
  156. using System.Linq;
  157. using System.Text;
  158. using System.Threading.Tasks;
  159.  
  160. namespace s3l2 {
  161.     enum Subject {
  162.         Informatics,
  163.         Math,
  164.         Russian
  165.     }
  166.     class TextBook : Book {
  167.         int _grade; //класс, на который рассчитан учебник
  168.         Subject _subject; //предмет, по которому данный учебник
  169.  
  170.         public TextBook(string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject) :
  171.             base(name, contents, pagesCount, lang, author, owner, circulation) {
  172.             Grade = grade;
  173.             Subject = subject;
  174.         }
  175.         public TextBook() : base() {
  176.             Grade = 1;
  177.             Subject = Subject.Informatics;
  178.         }
  179.         public int Grade { //тираж
  180.             get {
  181.                 return _grade;
  182.             }
  183.             private set { //невозможно добавить или убрать страницы книги после печати
  184.                 if (value < 1 || value > 11) {
  185.                     this.LogError("Некорректный класс учебника. Пересоздайте объект");
  186.                     _grade = 1;
  187.                 } else
  188.                     _grade = value;
  189.             }
  190.         }
  191.         public Subject Subject { //количество страниц
  192.             get { return _subject; }
  193.             private set { _subject = value; }
  194.         }
  195.  
  196.  
  197.         public override void PrintInfo() {
  198.             base.PrintInfo();
  199.             Console.WriteLine($"Является учебником для {Grade} класса");
  200.             Console.WriteLine($"Учебный предмет: {Subject}");
  201.         }
  202.  
  203.         public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
  204.             base.PrintContents();
  205.         }
  206.         public override void Open() { //переопределяем абстрактный метод open()
  207.             Console.WriteLine("Открываем учебник...");
  208.             //...
  209.         }
  210.  
  211.         public override string ToString() {
  212.             return ($"Учебник для {Grade} класса по предмету {Subject}: {Name}(Автор: {Author}, Владелец: {Owner}, Тираж: {Circulation}. Язык: {Lang}, {PagesCount} страниц)");//HH:mm
  213.         }
  214.     }
  215.  
  216. }
  217.  
  218.  
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227.  
  228.  
  229.  
  230. using System;
  231. using System.Collections.Generic;
  232. using System.IO;
  233. using System.Linq;
  234. using System.Text;
  235. using System.Threading.Tasks;
  236.  
  237. namespace s3l2 {
  238.     //Кротов Сергей КБ-21СО Лабораторная №1 Вариант 9. Печатное издание
  239.     enum Language {
  240.         English,
  241.         Russian,
  242.         Deutsch,
  243.         Japanese
  244.     }
  245.    
  246.     abstract class PrintedMatter {
  247.         string _name; //название печатного издания
  248.         string _contents; //текст печатного издания
  249.         int _pagesCount; //количество страниц
  250.         Language _lang; //язык
  251.  
  252.  
  253.         public string Name { //название печатного издания
  254.             get {return _name;}
  255.             private set {
  256.                 if (string.IsNullOrEmpty(value)) {
  257.                     Console.WriteLine("Установлено значение по умолчанию");
  258.                     _name = "Unknown";
  259.                 } else
  260.                     _name = value;
  261.             }
  262.         }
  263.  
  264.         public string Contents { //текст печатного издания
  265.             get {return _contents;}
  266.             private set { //никто не должен менять содержание книги
  267.                 if (string.IsNullOrEmpty(value)) {
  268.                     this.LogError("Не введено содержание издания. Пересоздайте объект");
  269.                     _contents = "";
  270.                 } else
  271.                     _contents = value;
  272.             }
  273.         }
  274.  
  275.         public int PagesCount { //количество страниц
  276.             get {return _pagesCount;}
  277.             private set { //невозможно добавить или убрать страницы книги после печати
  278.                 if (value <= 0) {
  279.                     Console.WriteLine("Установлено значение по умолчанию");
  280.                     _pagesCount = 1; //как минимум одна страница, чтобы держать в руках
  281.                 } else
  282.                     _pagesCount = value;
  283.             }
  284.         }
  285.         public Language Lang{ //количество страниц
  286.             get {return _lang;}
  287.             private set {_lang = value;}
  288.         }
  289.  
  290.         protected void LogError(string msg) {
  291.             Console.ForegroundColor = ConsoleColor.Red;
  292.             Console.WriteLine($"Ошибка в классе {this.GetType()}: {msg}");
  293.             Console.ForegroundColor = ConsoleColor.White;
  294.         }
  295.  
  296.         public PrintedMatter(string name, string contents, int pagesCount, Language lang) {
  297.             Name = name; //название печатного издания
  298.             Contents = contents; //текст печатного издания
  299.             PagesCount = pagesCount; //количество страниц
  300.             Lang = lang; //язык
  301.         }
  302.  
  303.         public PrintedMatter() : this("Unknown book", "Empty page", 1, Language.Russian) { }
  304.  
  305.         public int GetWordsCount() {
  306.             int cnt = 0, letters = 0;
  307.             for (int i = 0; i < Contents.Length; i++) {
  308.                 if (char.IsLetterOrDigit(Contents[i]))
  309.                     letters++;
  310.                 else {
  311.                     if (letters > 0)
  312.                         cnt++;
  313.                     letters = 0;
  314.                 }
  315.             }
  316.             if (letters > 0)
  317.                 cnt++;
  318.             return cnt;
  319.         }
  320.  
  321.         public abstract void Open(); //абстрактный метод open(), который должны реализовать в потомках
  322.  
  323.         public virtual void PrintContents() {
  324.             Console.ForegroundColor = ConsoleColor.Yellow;
  325.             Console.WriteLine(Contents);
  326.             Console.ForegroundColor = ConsoleColor.White;
  327.         }
  328.         public virtual void PrintInfo() {
  329.             Console.WriteLine($"Название: {Name}");
  330.             Console.WriteLine($"Язык: {Lang}");
  331.             Console.WriteLine($"Количество страниц: {PagesCount}");
  332.         }
  333.  
  334.         //overriding
  335.         public override string ToString() {
  336.             return ($"Печатное издание {Name}(Язык: {Lang}, {PagesCount} страниц)");//HH:mm
  337.         }
  338.  
  339.         public static bool operator >(PrintedMatter t1, PrintedMatter t2) {
  340.             return t1.Name.CompareTo(t2.Name) > 0;
  341.         }
  342.         public static bool operator <(PrintedMatter t1, PrintedMatter t2) {
  343.             return t1.Name.CompareTo(t2.Name) < 0;
  344.         }
  345.         public static bool operator >=(PrintedMatter t1, PrintedMatter t2) {
  346.             return t1.Name.CompareTo(t2.Name) > 0;
  347.         }
  348.         public static bool operator <=(PrintedMatter t1, PrintedMatter t2) {
  349.             return t1.Name.CompareTo(t2.Name) < 0;
  350.         }
  351.  
  352.         public static bool operator ==(PrintedMatter t1, PrintedMatter t2) {
  353.             return t1.Name.Equals(t2.Name);
  354.         }
  355.         public static bool operator !=(PrintedMatter t1, PrintedMatter t2) {
  356.             return !t1.Name.Equals(t2.Name);
  357.         }
  358.         public override bool Equals(object o) {
  359.             if (o is PrintedMatter)
  360.                 return (((PrintedMatter)o).Name == this.Name);
  361.             return false;
  362.         }
  363.         public override int GetHashCode() {
  364.             return this.ToString().GetHashCode();
  365.         }
  366.     }
  367.  
  368.     class Program {
  369.         static Language GetLanguage(string str) {
  370.             switch (str) {
  371.                 case "English":
  372.                     return Language.English;
  373.                 case "Russian":
  374.                     return Language.Russian;
  375.                 case "Deutsch":
  376.                     return Language.Deutsch;
  377.                 case "Japanese":
  378.                     return Language.Japanese;
  379.             }
  380.             return Language.Russian;
  381.         }
  382.         static Subject GetSubject(string str) {
  383.             switch (str) {
  384.                 case "Informatics":
  385.                     return Subject.Informatics;
  386.                 case "Math":
  387.                     return Subject.Math;
  388.                 case "Russian":
  389.                     return Subject.Russian;
  390.             }
  391.             return Subject.Informatics;
  392.         }
  393.         static string GetContents(string str) { //для сохранения новых строк
  394.             return str.Replace(("\\n"), "\n");
  395.         }
  396.         static void Main(string[] args) {
  397.             //contents = "     iodfj fdjio ler k  ааббб..куаы/341 ";
  398.             PrintedMatter[] Matters;
  399.             using (StreamReader sr = new StreamReader("input.txt", Encoding.Default)) {
  400.                 int n = int.Parse(sr.ReadLine());
  401.                 Matters = new PrintedMatter[n];
  402.                 for (int i = 0; i < n; i++) {
  403.                     string type = sr.ReadLine();
  404.                     string[] info;
  405.                     switch (type) {
  406.                         case "Book":
  407.                             info = new string[7];
  408.                             for (int j = 0; j < 7; j++)
  409.                                 info[j] = sr.ReadLine();
  410.                             //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation
  411.                             Matters[i] = new Book(info[0], GetContents(info[1]), int.Parse(info[2]), GetLanguage(info[3]), info[4], info[5], int.Parse(info[6]));
  412.                             break;
  413.                         case "NewsPaper":
  414.                             info = new string[6];
  415.                             for (int j = 0; j < 6; j++)
  416.                                 info[j] = sr.ReadLine();
  417.                             //string name, string contents, int pagesCount, Language lang, string publication, int printDate
  418.                             Matters[i] = new NewsPaper(info[0], GetContents(info[1]), int.Parse(info[2]), GetLanguage(info[3]), info[4], int.Parse(info[5]));
  419.                             break;
  420.                         case "TextBook":
  421.                             info = new string[9];
  422.                             for (int j = 0; j < 9; j++)
  423.                                 info[j] = sr.ReadLine();
  424.                             //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject
  425.                             Matters[i] = new TextBook(info[0], GetContents(info[1]), int.Parse(info[2]), GetLanguage(info[3]), info[4], info[5], int.Parse(info[6]), int.Parse(info[7]), GetSubject(info[8]));
  426.                             break;
  427.                     }
  428.                     sr.ReadLine();
  429.                 }
  430.             }
  431.             foreach (PrintedMatter Matter in Matters) {
  432.                 Console.WriteLine(Matter); //Перегрузка ToString
  433.                 Console.WriteLine();
  434.                 Matter.PrintInfo(); //Переопределённый виртуальный метод
  435.                 Console.WriteLine();
  436.                 Matter.Open();     //Реализованный абстрактный метод
  437.                 Console.WriteLine();
  438.                 Matter.PrintContents(); //Переопределённый виртуальный метод
  439.                 Console.WriteLine();
  440.  
  441.                 Console.WriteLine();
  442.                 Console.WriteLine();
  443.             }
  444.  
  445.             /*
  446.             var EmptyBook = new PrintedMatter();
  447.  
  448.             EmptyBook.PrintInfo();
  449.             Console.WriteLine();
  450.             EmptyBook.PrintContents();
  451.  
  452.             Console.WriteLine();
  453.             Console.WriteLine();
  454.             Console.WriteLine();
  455.  
  456.             string contents = "Компьютерное издательство “Диалектика”\nПеревод с английского и редакция Ю.Н.Артеменко\nПо общим вопросам обращайтесь в издательство “Диалектика” по адресу:\ninfo @dialektika.com, http:\nТроелсен, Эндрю, Джепикс, Филипп.Т70 Язык программирования C# 7 и платформы .NET и .NET Core, 8-е изд. : Пер. с\nангл. — СПб. : ООО “Диалектика”, 2018 — 1328 с. : ил. — Парал.тит.англ.\nISBN 978 - 5 - 6040723 - 1 - 8(рус.)\nББК 32.973";
  457.  
  458.             var Csharp = new PrintedMatter(
  459.                 "Язык программирования C# 7 и платформы .NET и .NET Core ",
  460.                 "Троелсен, Джепикс",
  461.                 contents,
  462.                 "Библиотека ЯрГУ",
  463.                 1330,
  464.                 Language.Russian,
  465.                 PrintedMatterType.book,
  466.                 new DateTime(2018, 1, 1, 1, 0, 0)
  467.             );
  468.  
  469.             Csharp.PrintContents();
  470.             Console.WriteLine();
  471.             Csharp.PrintInfo();
  472.  
  473.             Console.WriteLine();
  474.             Console.WriteLine();
  475.  
  476.             var GoodBook = new PrintedMatter("Suvmer's book", "Кротов Сергей", "My profile on github: https://github.com/suvmer"); //8 words
  477.  
  478.             GoodBook.PrintContents();
  479.             Console.WriteLine();
  480.             GoodBook.PrintInfo();
  481.             Console.WriteLine();
  482.             Console.WriteLine($"Владелец книги {GoodBook.Name}: {GoodBook.Owner}");
  483.             GoodBook.Owner = ""; //Ошибка в консоли
  484.             GoodBook.Owner = "Сергей Кротов";
  485.             Console.WriteLine($"Книга {GoodBook.Name} перешла во владение человеку: {GoodBook.Owner}");
  486.  
  487.             Console.WriteLine();
  488.             Console.WriteLine($"Количество слов в тексте книги  {Csharp}:");
  489.             Console.WriteLine(Csharp.GetWordsCount());
  490.  
  491.             Console.WriteLine($"Количество слов в тексте книги  {GoodBook}:");
  492.             Console.WriteLine(GoodBook.GetWordsCount());
  493.  
  494.             Console.ForegroundColor = ConsoleColor.Yellow;
  495.             if (GoodBook > Csharp) {
  496.                 Console.WriteLine($"Книга автора {GoodBook.Author} больше по словам, чем книга {Csharp.Name}");
  497.             } else if (GoodBook == Csharp) {
  498.                 Console.WriteLine($"У книг одинаковое количество слов");
  499.             } else {
  500.                 Console.WriteLine($"Наибольшее количество слов в книге {Csharp.Name}");
  501.             }
  502.             Console.ForegroundColor = ConsoleColor.White;
  503.  
  504.             */
  505.             Console.ReadKey();
  506.         }
  507.     }
  508.     /*
  509.     class Employee
  510.     {
  511.         public static string CompanyName;
  512.         static Employee()
  513.         {
  514.             CompanyName = "ЯрГУ";
  515.         }
  516.     }*/
  517. }
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524. using System;
  525. using System.Collections.Generic;
  526. using System.Linq;
  527. using System.Text;
  528. using System.Threading.Tasks;
  529.  
  530. namespace s3l2 {
  531.     class Book : PrintedMatter {
  532.         string _author; //автор книги
  533.         string _owner; //владелец книги
  534.         int _circulation; //тираж
  535.  
  536.         public string Author { //Автор книги
  537.             get {
  538.                 return _author;
  539.             }
  540.             private set {
  541.                 if (string.IsNullOrEmpty(value)) {
  542.                     this.LogError("Не введен автор книги. Пересоздайте объект");
  543.                     _author = "Unknown author";
  544.                 } else
  545.                     _author = value;
  546.             }
  547.         }
  548.         public string Owner { //Владелец книги
  549.             get {
  550.                 return _owner;
  551.             }
  552.             set {
  553.                 if (string.IsNullOrEmpty(value)) {
  554.                     this.LogError("Не введен владелец книги. Пересоздайте объект");
  555.                     _owner = "";
  556.                 } else
  557.                     _owner = value;
  558.             }
  559.         }
  560.         public int Circulation { //тираж
  561.             get {
  562.                 return _circulation;
  563.             }
  564.             private set { //невозможно добавить или убрать страницы книги после печати
  565.                 if (value <= 0) {
  566.                     this.LogError("Некорректный тираж книги. Пересоздайте объект");
  567.                     _circulation = 1;
  568.                 } else
  569.                     _circulation = value;
  570.             }
  571.         }
  572.  
  573.         public Book(string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation) : base(name, contents, pagesCount, lang) {
  574.             Author = author;
  575.             Owner = owner;
  576.             Circulation = circulation;
  577.         }
  578.         public Book() : base() {
  579.             Author = "ЯрГУ";
  580.             Owner = "Библиотека ЯрГУ";
  581.             Circulation = 1;
  582.         }
  583.  
  584.  
  585.         public override void PrintInfo() {
  586.             Console.WriteLine($"Информация о книге: {Name}");
  587.             Console.WriteLine($"Автор: {Author}");
  588.             Console.WriteLine($"Владелец: {Owner}");
  589.             Console.WriteLine($"Тираж: {Circulation}");
  590.             base.PrintInfo();
  591.         }
  592.  
  593.         public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
  594.             Console.WriteLine($"Содержание книги “{Name}”:");
  595.             base.PrintContents();
  596.         }
  597.  
  598.         public override void Open() { //переопределяем абстрактный метод open()
  599.             Console.WriteLine("Открываем книгу...");
  600.             //...
  601.         }
  602.  
  603.         public override string ToString() {
  604.             return ($"Книга {Name}(Автор: {Author}, Владелец: {Owner}, Тираж: {Circulation}. Язык: {Lang}, {PagesCount} страниц)");//HH:mm
  605.         }
  606.  
  607.     }
  608. }
  609.  
  610.  
  611.  
  612.  
  613.  
  614.  
  615.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement