Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 3
- Book
- Язык программирования C# 7 и платформы .NET и .NET Core
- ...Перевод с английского и редакция Ю.Н.Артеменко\nПо общим вопросам обращайтесь в издательство “Диалектика” по адресу:\ninform...
- 1330
- Russian
- Троелсен, Джепикс
- Библиотека ЯрГУ
- 100000
- NewsPaper
- Известия
- ...Свежие новости: в Ярославле по адресу Союзная 144 студенты начали изучать ООП...
- 5
- Russian
- ЯрГУ
- 20
- TextBook
- Математика
- ..Параграф 5. Простые и составные числа
- 95
- Russian
- Н. Я. Виленкин
- Кротов Сергей
- 200000
- 8
- Math
- Book
- //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation
- NewsPaper
- //string name, string contents, int pagesCount, Language lang, string publication, int printDate
- TextBook
- //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace s3l2 {
- class NewsPaper : PrintedMatter {
- string _publication; //издательство, выпустившее газету
- int _printDate; //день выпуска газеты
- public NewsPaper(string name, string contents, int pagesCount, Language lang, string publication, int printDate) : base(name, contents, pagesCount, lang) {
- Publication = publication;
- PrintDate = printDate;
- }
- public NewsPaper() : base() {
- Publication = "ЯрГУ";
- PrintDate = DateTime.Now.Day;
- //PrintDate = DateTime.Now;
- }
- public override void PrintInfo() {
- Console.WriteLine($"Информация о газете: {Name}");
- Console.WriteLine($"Издательство: {Publication}");
- base.PrintInfo();
- Console.WriteLine($"День выпуска газеты: {PrintDate}");
- //Console.WriteLine($"Дата издания газеты: {PrintDate.ToString("dd.MM.yyyy")}");
- }
- public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
- Console.WriteLine($"Содержание газеты “{Name}”:");
- base.PrintContents();
- }
- public override void Open() { //переопределяем абстрактный метод open()
- Console.WriteLine("Отображаем газету... ");
- //...
- }
- public string Publication { //название печатного издания
- get {
- return _publication;
- }
- private set {
- if (string.IsNullOrEmpty(value)) {
- this.LogError("Не задано название издательства газеты");
- _publication = "Unknown";
- } else
- _publication = value;
- }
- }
- public int PrintDate { //тираж
- get {
- return _printDate;
- }
- private set { //невозможно добавить или убрать страницы книги после печати
- if (value < 1 || value > 31) {
- this.LogError("Некорректный день выпуска газеты. Пересоздайте объект");
- _printDate = 1;
- } else
- _printDate = value;
- }
- }
- public override string ToString() {
- return ($"Газета {Name} издательства {Publication}(Язык: {Lang}, {PagesCount} страниц, день выпуска: {PrintDate})");//HH:mm
- }
- /*public DateTime PrintDate { //год(дата) издания
- get {
- return _printDate;
- }
- private set {
- if (_printDate > DateTime.Now) { //нельзя напечатать издание в будущем
- Console.WriteLine("Газете установлена текущая дата");
- _printDate = DateTime.Now;
- } else
- _printDate = value;
- }
- }*/
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace s3l2 {
- enum Subject {
- Informatics,
- Math,
- Russian
- }
- class TextBook : Book {
- int _grade; //класс, на который рассчитан учебник
- Subject _subject; //предмет, по которому данный учебник
- public TextBook(string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject) :
- base(name, contents, pagesCount, lang, author, owner, circulation) {
- Grade = grade;
- Subject = subject;
- }
- public TextBook() : base() {
- Grade = 1;
- Subject = Subject.Informatics;
- }
- public int Grade { //тираж
- get {
- return _grade;
- }
- private set { //невозможно добавить или убрать страницы книги после печати
- if (value < 1 || value > 11) {
- this.LogError("Некорректный класс учебника. Пересоздайте объект");
- _grade = 1;
- } else
- _grade = value;
- }
- }
- public Subject Subject { //количество страниц
- get { return _subject; }
- private set { _subject = value; }
- }
- public override void PrintInfo() {
- base.PrintInfo();
- Console.WriteLine($"Является учебником для {Grade} класса");
- Console.WriteLine($"Учебный предмет: {Subject}");
- }
- public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
- base.PrintContents();
- }
- public override void Open() { //переопределяем абстрактный метод open()
- Console.WriteLine("Открываем учебник...");
- //...
- }
- public override string ToString() {
- return ($"Учебник для {Grade} класса по предмету {Subject}: {Name}(Автор: {Author}, Владелец: {Owner}, Тираж: {Circulation}. Язык: {Lang}, {PagesCount} страниц)");//HH:mm
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace s3l2 {
- //Кротов Сергей КБ-21СО Лабораторная №1 Вариант 9. Печатное издание
- enum Language {
- English,
- Russian,
- Deutsch,
- Japanese
- }
- abstract class PrintedMatter {
- string _name; //название печатного издания
- string _contents; //текст печатного издания
- int _pagesCount; //количество страниц
- Language _lang; //язык
- public string Name { //название печатного издания
- get {return _name;}
- private set {
- if (string.IsNullOrEmpty(value)) {
- Console.WriteLine("Установлено значение по умолчанию");
- _name = "Unknown";
- } else
- _name = value;
- }
- }
- public string Contents { //текст печатного издания
- get {return _contents;}
- private set { //никто не должен менять содержание книги
- if (string.IsNullOrEmpty(value)) {
- this.LogError("Не введено содержание издания. Пересоздайте объект");
- _contents = "";
- } else
- _contents = value;
- }
- }
- public int PagesCount { //количество страниц
- get {return _pagesCount;}
- private set { //невозможно добавить или убрать страницы книги после печати
- if (value <= 0) {
- Console.WriteLine("Установлено значение по умолчанию");
- _pagesCount = 1; //как минимум одна страница, чтобы держать в руках
- } else
- _pagesCount = value;
- }
- }
- public Language Lang{ //количество страниц
- get {return _lang;}
- private set {_lang = value;}
- }
- protected void LogError(string msg) {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine($"Ошибка в классе {this.GetType()}: {msg}");
- Console.ForegroundColor = ConsoleColor.White;
- }
- public PrintedMatter(string name, string contents, int pagesCount, Language lang) {
- Name = name; //название печатного издания
- Contents = contents; //текст печатного издания
- PagesCount = pagesCount; //количество страниц
- Lang = lang; //язык
- }
- public PrintedMatter() : this("Unknown book", "Empty page", 1, Language.Russian) { }
- public int GetWordsCount() {
- int cnt = 0, letters = 0;
- for (int i = 0; i < Contents.Length; i++) {
- if (char.IsLetterOrDigit(Contents[i]))
- letters++;
- else {
- if (letters > 0)
- cnt++;
- letters = 0;
- }
- }
- if (letters > 0)
- cnt++;
- return cnt;
- }
- public abstract void Open(); //абстрактный метод open(), который должны реализовать в потомках
- public virtual void PrintContents() {
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine(Contents);
- Console.ForegroundColor = ConsoleColor.White;
- }
- public virtual void PrintInfo() {
- Console.WriteLine($"Название: {Name}");
- Console.WriteLine($"Язык: {Lang}");
- Console.WriteLine($"Количество страниц: {PagesCount}");
- }
- //overriding
- public override string ToString() {
- return ($"Печатное издание {Name}(Язык: {Lang}, {PagesCount} страниц)");//HH:mm
- }
- public static bool operator >(PrintedMatter t1, PrintedMatter t2) {
- return t1.Name.CompareTo(t2.Name) > 0;
- }
- public static bool operator <(PrintedMatter t1, PrintedMatter t2) {
- return t1.Name.CompareTo(t2.Name) < 0;
- }
- public static bool operator >=(PrintedMatter t1, PrintedMatter t2) {
- return t1.Name.CompareTo(t2.Name) > 0;
- }
- public static bool operator <=(PrintedMatter t1, PrintedMatter t2) {
- return t1.Name.CompareTo(t2.Name) < 0;
- }
- public static bool operator ==(PrintedMatter t1, PrintedMatter t2) {
- return t1.Name.Equals(t2.Name);
- }
- public static bool operator !=(PrintedMatter t1, PrintedMatter t2) {
- return !t1.Name.Equals(t2.Name);
- }
- public override bool Equals(object o) {
- if (o is PrintedMatter)
- return (((PrintedMatter)o).Name == this.Name);
- return false;
- }
- public override int GetHashCode() {
- return this.ToString().GetHashCode();
- }
- }
- class Program {
- static Language GetLanguage(string str) {
- switch (str) {
- case "English":
- return Language.English;
- case "Russian":
- return Language.Russian;
- case "Deutsch":
- return Language.Deutsch;
- case "Japanese":
- return Language.Japanese;
- }
- return Language.Russian;
- }
- static Subject GetSubject(string str) {
- switch (str) {
- case "Informatics":
- return Subject.Informatics;
- case "Math":
- return Subject.Math;
- case "Russian":
- return Subject.Russian;
- }
- return Subject.Informatics;
- }
- static string GetContents(string str) { //для сохранения новых строк
- return str.Replace(("\\n"), "\n");
- }
- static void Main(string[] args) {
- //contents = " iodfj fdjio ler k ааббб..куаы/341 ";
- PrintedMatter[] Matters;
- using (StreamReader sr = new StreamReader("input.txt", Encoding.Default)) {
- int n = int.Parse(sr.ReadLine());
- Matters = new PrintedMatter[n];
- for (int i = 0; i < n; i++) {
- string type = sr.ReadLine();
- string[] info;
- switch (type) {
- case "Book":
- info = new string[7];
- for (int j = 0; j < 7; j++)
- info[j] = sr.ReadLine();
- //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation
- Matters[i] = new Book(info[0], GetContents(info[1]), int.Parse(info[2]), GetLanguage(info[3]), info[4], info[5], int.Parse(info[6]));
- break;
- case "NewsPaper":
- info = new string[6];
- for (int j = 0; j < 6; j++)
- info[j] = sr.ReadLine();
- //string name, string contents, int pagesCount, Language lang, string publication, int printDate
- Matters[i] = new NewsPaper(info[0], GetContents(info[1]), int.Parse(info[2]), GetLanguage(info[3]), info[4], int.Parse(info[5]));
- break;
- case "TextBook":
- info = new string[9];
- for (int j = 0; j < 9; j++)
- info[j] = sr.ReadLine();
- //string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation, int grade, Subject subject
- 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]));
- break;
- }
- sr.ReadLine();
- }
- }
- foreach (PrintedMatter Matter in Matters) {
- Console.WriteLine(Matter); //Перегрузка ToString
- Console.WriteLine();
- Matter.PrintInfo(); //Переопределённый виртуальный метод
- Console.WriteLine();
- Matter.Open(); //Реализованный абстрактный метод
- Console.WriteLine();
- Matter.PrintContents(); //Переопределённый виртуальный метод
- Console.WriteLine();
- Console.WriteLine();
- Console.WriteLine();
- }
- /*
- var EmptyBook = new PrintedMatter();
- EmptyBook.PrintInfo();
- Console.WriteLine();
- EmptyBook.PrintContents();
- Console.WriteLine();
- Console.WriteLine();
- Console.WriteLine();
- 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";
- var Csharp = new PrintedMatter(
- "Язык программирования C# 7 и платформы .NET и .NET Core ",
- "Троелсен, Джепикс",
- contents,
- "Библиотека ЯрГУ",
- 1330,
- Language.Russian,
- PrintedMatterType.book,
- new DateTime(2018, 1, 1, 1, 0, 0)
- );
- Csharp.PrintContents();
- Console.WriteLine();
- Csharp.PrintInfo();
- Console.WriteLine();
- Console.WriteLine();
- var GoodBook = new PrintedMatter("Suvmer's book", "Кротов Сергей", "My profile on github: https://github.com/suvmer"); //8 words
- GoodBook.PrintContents();
- Console.WriteLine();
- GoodBook.PrintInfo();
- Console.WriteLine();
- Console.WriteLine($"Владелец книги {GoodBook.Name}: {GoodBook.Owner}");
- GoodBook.Owner = ""; //Ошибка в консоли
- GoodBook.Owner = "Сергей Кротов";
- Console.WriteLine($"Книга {GoodBook.Name} перешла во владение человеку: {GoodBook.Owner}");
- Console.WriteLine();
- Console.WriteLine($"Количество слов в тексте книги {Csharp}:");
- Console.WriteLine(Csharp.GetWordsCount());
- Console.WriteLine($"Количество слов в тексте книги {GoodBook}:");
- Console.WriteLine(GoodBook.GetWordsCount());
- Console.ForegroundColor = ConsoleColor.Yellow;
- if (GoodBook > Csharp) {
- Console.WriteLine($"Книга автора {GoodBook.Author} больше по словам, чем книга {Csharp.Name}");
- } else if (GoodBook == Csharp) {
- Console.WriteLine($"У книг одинаковое количество слов");
- } else {
- Console.WriteLine($"Наибольшее количество слов в книге {Csharp.Name}");
- }
- Console.ForegroundColor = ConsoleColor.White;
- */
- Console.ReadKey();
- }
- }
- /*
- class Employee
- {
- public static string CompanyName;
- static Employee()
- {
- CompanyName = "ЯрГУ";
- }
- }*/
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace s3l2 {
- class Book : PrintedMatter {
- string _author; //автор книги
- string _owner; //владелец книги
- int _circulation; //тираж
- public string Author { //Автор книги
- get {
- return _author;
- }
- private set {
- if (string.IsNullOrEmpty(value)) {
- this.LogError("Не введен автор книги. Пересоздайте объект");
- _author = "Unknown author";
- } else
- _author = value;
- }
- }
- public string Owner { //Владелец книги
- get {
- return _owner;
- }
- set {
- if (string.IsNullOrEmpty(value)) {
- this.LogError("Не введен владелец книги. Пересоздайте объект");
- _owner = "";
- } else
- _owner = value;
- }
- }
- public int Circulation { //тираж
- get {
- return _circulation;
- }
- private set { //невозможно добавить или убрать страницы книги после печати
- if (value <= 0) {
- this.LogError("Некорректный тираж книги. Пересоздайте объект");
- _circulation = 1;
- } else
- _circulation = value;
- }
- }
- public Book(string name, string contents, int pagesCount, Language lang, string author, string owner, int circulation) : base(name, contents, pagesCount, lang) {
- Author = author;
- Owner = owner;
- Circulation = circulation;
- }
- public Book() : base() {
- Author = "ЯрГУ";
- Owner = "Библиотека ЯрГУ";
- Circulation = 1;
- }
- public override void PrintInfo() {
- Console.WriteLine($"Информация о книге: {Name}");
- Console.WriteLine($"Автор: {Author}");
- Console.WriteLine($"Владелец: {Owner}");
- Console.WriteLine($"Тираж: {Circulation}");
- base.PrintInfo();
- }
- public override void PrintContents() { //переопределяем виртуальный метод PrintContents() (расширяем его возможности)
- Console.WriteLine($"Содержание книги “{Name}”:");
- base.PrintContents();
- }
- public override void Open() { //переопределяем абстрактный метод open()
- Console.WriteLine("Открываем книгу...");
- //...
- }
- public override string ToString() {
- return ($"Книга {Name}(Автор: {Author}, Владелец: {Owner}, Тираж: {Circulation}. Язык: {Lang}, {PagesCount} страниц)");//HH:mm
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement