blrmyfc

Untitled

Apr 2nd, 2019
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.21 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. //В новой версии класса Student определить
  8.  
  9. //* итератор для последовательного перебора всех элементов(объектов типа object) из списков зачетов и экзаменов(объединение);
  10.  
  11. //* итератор c параметром для перебора экзаменов(объектов типа Exam) с оценкой больше заданного значения.
  12. namespace ConsoleApp2
  13. {
  14. //реализовать интерфейс IDateAndCopy
  15. class Person : IDateAndCopy
  16.  
  17. {
  18.  
  19. private string name;
  20.  
  21. private string lastName;
  22.  
  23. private DateTime bdate;
  24.  
  25. public Person(string name, string lastName, DateTime bdate)
  26.  
  27. {
  28.  
  29. this.name = name;
  30.  
  31. this.lastName = lastName;
  32.  
  33. this.bdate = bdate;
  34.  
  35. }
  36.  
  37. public Person()
  38.  
  39. {
  40.  
  41. name = "Gulshat";
  42.  
  43. lastName = "Sabitova";
  44.  
  45. bdate = new DateTime(1999, 3, 22);
  46.  
  47. }
  48.  
  49. public string Name
  50.  
  51. {
  52.  
  53. get { return name; }
  54.  
  55. set { name = value; }
  56.  
  57. }
  58.  
  59. public string LastName
  60.  
  61. {
  62.  
  63. get { return lastName; }
  64.  
  65. set { lastName = value; }
  66.  
  67. }
  68.  
  69. public DateTime Date
  70.  
  71. {
  72.  
  73. get { return bdate; }
  74.  
  75. set { bdate = value; }
  76.  
  77. }
  78.  
  79. public int Year
  80.  
  81. {
  82.  
  83. get { return bdate.Year; }
  84.  
  85. set { bdate = new DateTime(value, bdate.Month, bdate.Day); }
  86.  
  87. }
  88.  
  89. public override string ToString()
  90.  
  91. {
  92.  
  93. return "Имя: " + name + "\n" + "Фамилия: " + lastName + "\n" + "Дата рождения: " + bdate.ToShortDateString();
  94.  
  95. }
  96.  
  97. public virtual string ToShortString()
  98.  
  99. {
  100.  
  101. return "Имя: " + name + "\n" + "Фамилия: " + lastName;
  102.  
  103. }
  104. //переопределить метод virtial bool Equals (object obj)
  105. public override bool Equals(Object obj)
  106.  
  107. {
  108.  
  109. Person person = (Person)obj;
  110.  
  111. bool value = false;
  112.  
  113. if (obj != null)
  114.  
  115. if (name.Equals(person.name))
  116.  
  117. if (lastName.Equals(person.lastName))
  118.  
  119. if (bdate.Equals(person.bdate))
  120.  
  121. value = true;
  122.  
  123. return value;
  124.  
  125. }
  126. //переопределить виртуальный метод int GetHashCode()
  127. public override int GetHashCode()
  128.  
  129. {
  130.  
  131. return name.Length + lastName.Length + bdate.Day + bdate.Month + bdate.Year;
  132.  
  133. }
  134. // определить операции == и != так, чтобы равенство объектов типа Person трактовалось как совпадение всех данных объектов, а не ссылок на объекты Person
  135.  
  136. public static bool operator ==(Person p1, Person p2)
  137.  
  138. {
  139.  
  140. bool result = false;
  141.  
  142. if (p1.name.Equals(p2.name))
  143.  
  144. if (p1.lastName.Equals(p2.lastName))
  145.  
  146. if (p1.bdate.Equals(p2.bdate))
  147.  
  148. result = true;
  149.  
  150. return result;
  151.  
  152. }
  153.  
  154. public static bool operator !=(Person p1, Person p2)
  155.  
  156. {
  157.  
  158. bool result = true;
  159.  
  160. if (p1.name.Equals(p2.name))
  161.  
  162. if (p1.lastName.Equals(p2.lastName))
  163.  
  164. if (p1.bdate.Equals(p2.bdate))
  165.  
  166. result = false;
  167.  
  168. return result;
  169.  
  170. }
  171. //определить виртуальный метод object DeepCopy();
  172. public object DeepCopy()
  173.  
  174. {
  175.  
  176. Person person = new Person(name, lastName, bdate);
  177.  
  178. return person;
  179.  
  180. }
  181.  
  182. }
  183. //Определить класс Test, который имеет два открытых автореализуемых свойства, доступных для чтения и записи
  184.  
  185. class Test : IDateAndCopy
  186.  
  187. {
  188. //свойство типа string, в котором хранится название предмет
  189. string name;
  190. //свойство типа bool для информации о том, сдан зачет или нет
  191. bool resultTest;
  192.  
  193. DateTime date;
  194. //конструктор c параметрами типа string и bool для инициализации свойств класса
  195. public Test(string name, bool resultTest, DateTime date)
  196.  
  197. {
  198.  
  199. this.name = name;
  200.  
  201. this.resultTest = resultTest;
  202.  
  203. this.date = date;
  204.  
  205. }
  206. //конструктор без параметров, инициализирующий все свойства класса некоторыми значениями по умолчанию
  207. public Test()
  208.  
  209. {
  210.  
  211. name = "Maths";
  212.  
  213. resultTest = true;
  214.  
  215. date = new DateTime(2019, 1, 1);
  216.  
  217. }
  218.  
  219. public DateTime Date
  220.  
  221. {
  222.  
  223. get { return date; }
  224.  
  225. set { date = value; }
  226.  
  227. }
  228. //перегруженную(override) версию виртуального метода string ToString() для формирования строки со значениями всех свойств класс
  229.  
  230. public override string ToString()
  231.  
  232. {
  233.  
  234. return "Название зачета: " + name + "\n Результат " + resultTest.ToString() + "\n Дата " + date.ToShortDateString();
  235.  
  236. }
  237.  
  238. public object DeepCopy()
  239.  
  240. {
  241.  
  242. Test test = new Test(name, resultTest, date);
  243.  
  244. return test;
  245.  
  246. }
  247.  
  248. }
  249.  
  250. class Exam : IDateAndCopy
  251.  
  252. {
  253.  
  254. string name;
  255.  
  256. int rating;
  257.  
  258. DateTime dateExam;
  259.  
  260. public Exam(string name, int rating, DateTime dateExam)
  261.  
  262. {
  263.  
  264. this.name = name;
  265.  
  266. this.rating = rating;
  267.  
  268. this.dateExam = dateExam;
  269.  
  270. }
  271.  
  272. public Exam()
  273.  
  274. {
  275.  
  276. name = "Maths";
  277.  
  278. rating = 5;
  279.  
  280. dateExam = new DateTime(2019, 1, 1);
  281.  
  282. }
  283.  
  284. public string Name
  285.  
  286. {
  287.  
  288. get { return name; }
  289.  
  290. set { name = value; }
  291.  
  292. }
  293.  
  294. public int Rating
  295.  
  296. {
  297.  
  298. get { return rating; }
  299.  
  300. set { rating = value; }
  301.  
  302. }
  303.  
  304. public DateTime Date
  305.  
  306. {
  307.  
  308. get { return dateExam; }
  309.  
  310. set { dateExam = value; }
  311.  
  312. }
  313.  
  314. public override string ToString()
  315.  
  316. {
  317.  
  318. return "Название экзамена: " + name + "\n оценка: " + rating.ToString() + "\n Дата экзамена: " + dateExam.ToShortDateString();
  319.  
  320. }
  321.  
  322. public object DeepCopy()
  323.  
  324. {
  325.  
  326. Exam exam = new Exam(this.name, this.rating, this.dateExam);
  327.  
  328. return exam;
  329.  
  330. }
  331.  
  332. public override bool Equals(Object obj)
  333.  
  334. {
  335.  
  336. Exam exam = (Exam)obj;
  337.  
  338. bool result = false;
  339.  
  340. if (name == exam.name)
  341.  
  342. if (rating == exam.rating)
  343.  
  344. if (dateExam == exam.dateExam)
  345.  
  346. result = true;
  347.  
  348. return result;
  349.  
  350. }
  351.  
  352. public static bool operator ==(Exam p1, Exam p2)
  353.  
  354. {
  355.  
  356. bool result = false;
  357.  
  358. if (p1.name == p2.name)
  359.  
  360. if (p1.rating == p2.rating)
  361.  
  362. if (p1.dateExam == p2.dateExam)
  363.  
  364. result = true;
  365.  
  366. return result;
  367.  
  368. }
  369.  
  370. public static bool operator !=(Exam p1, Exam p2)
  371.  
  372. {
  373.  
  374. bool result = true;
  375.  
  376. if (p1.name == p2.name)
  377.  
  378. if (p1.rating == p2.rating)
  379.  
  380. if (p1.dateExam == p2.dateExam)
  381.  
  382. result = false;
  383.  
  384. return result;
  385.  
  386. }
  387.  
  388. public override int GetHashCode()
  389.  
  390. {
  391.  
  392. return name.Length + rating + dateExam.Day + dateExam.Month + dateExam.Year;
  393.  
  394. }
  395.  
  396. }
  397. //Класс Student определить как производный от класса Person,реализовать интерфейс IDateAndCopy
  398. class Student : Person, IDateAndCopy
  399.  
  400. {
  401. //закрытое поле типа Education для информации о форме обучени
  402. private Education education;
  403. //закрытое поле типа int для номера группы
  404. private int numberGroup;
  405. //закрытое поле типа System.Collections.ArrayList, в котором хранится список зачетов (объекты типа Test
  406. private ArrayList listTests;
  407. //закрытое поле типа System.Collections.ArrayList для списка экзаменов (объекты типа Exam).
  408. private Exam[] exams;
  409. //конструктор c параметрами типа Person, Education, int для инициализации соответствующих полей класса
  410. public Student(Person person, Education education, int numberGroup)
  411.  
  412. {
  413.  
  414. Person = person;
  415.  
  416. this.education = education;
  417.  
  418. this.numberGroup = numberGroup;
  419.  
  420. exams = new Exam[0];
  421.  
  422. listTests = new ArrayList();
  423.  
  424. }
  425. //конструктор без параметров для инициализации по умолчанию;
  426. public Student()
  427.  
  428. {
  429.  
  430. Person = new Person();
  431.  
  432. education = Education.Bachelor;
  433.  
  434. numberGroup = 1;
  435.  
  436. exams = new Exam[0];
  437.  
  438. listTests = new ArrayList();
  439.  
  440. }
  441. //свойство типа Person
  442. public Person Person
  443.  
  444. {
  445. //метод get свойства возвращает объект типа Person, данные которого совпадают с данными подобъекта базового класса
  446. get { return (Person)this; }
  447. // метод set присваивает значения полям из подобъекта базового класса
  448. set
  449.  
  450. {
  451.  
  452. Name = value.Name;
  453.  
  454. LastName = value.LastName;
  455.  
  456. Date = value.Date;
  457.  
  458. }
  459.  
  460. }
  461. //свойство типа System.Collections.ArrayList с методами get и set для доступа к полю со списком экзаменов
  462. public ArrayList ListTests
  463.  
  464. {
  465.  
  466. get { return listTests; }
  467.  
  468. set { listTests = value; }
  469.  
  470. }
  471. //метод void AddExams ( params Exam[] ) для добавления элементов в список экзаменов
  472. public Exam[] Exams
  473.  
  474. {
  475.  
  476. get { return exams; }
  477.  
  478. set { exams = value; }
  479.  
  480. }
  481. //свойство типа double ( только с методом get), в котором вычисляется средний балл как среднее значение оценок в списке сданных экзаменов
  482.  
  483. public double AverageRating
  484.  
  485. {
  486.  
  487. get
  488.  
  489. {
  490.  
  491. int sum = 0;
  492.  
  493. for (int i = 0; i < exams.Length; i++)
  494.  
  495. {
  496.  
  497. sum += exams[i].Rating;
  498.  
  499. }
  500.  
  501. if (exams.Length != 0)
  502.  
  503. return sum / exams.Length;
  504.  
  505. else
  506.  
  507. return 0;
  508.  
  509. }
  510.  
  511. }
  512. //определить свойство типа int с методами get и set для доступа к полю с номером группы. В методе set бросить исключение,
  513. //если присваиваемое значение меньше или равно 100 или больше 599.При создании объекта- исключения использовать один из определенных
  514. //в библиотеке CLR классов- исключений, инициализировать объект-исключение с помощью конструктора с параметром типа string,
  515. //в сообщении передать информацию о допустимых границах для значения свойства.
  516. public int NumberGroup
  517.  
  518. {
  519.  
  520. get { return numberGroup; }
  521.  
  522. set
  523.  
  524. {
  525.  
  526. if (value <= 100 || value > 599)
  527.  
  528. throw new Exception("Номер группы должен быть меньше 599 и не равен 100");
  529.  
  530. }
  531.  
  532. }
  533.  
  534. public void AddExam(params Exam[] examAdd)
  535.  
  536. {
  537.  
  538. int Length = exams.Length;
  539.  
  540. Array.Resize<Exam>(ref exams, Length + examAdd.Length);
  541.  
  542. examAdd.CopyTo(exams, Length);
  543.  
  544. }
  545.  
  546.  
  547. public void AddTest(params Test[] tests)
  548.  
  549. {
  550.  
  551. listTests.AddRange(tests);
  552.  
  553. }
  554. //перегруженная версия виртуального метода string ToString() для формирования строки со значениями всех полей класса, включая список зачетов и экзаменов
  555. public override string ToString()
  556.  
  557. {
  558.  
  559. string result = base.ToString() + "\n Тип образования: " + education.ToString() + "\n Номер группы" + numberGroup.ToString() + "\n";
  560.  
  561. //if(exams.Length != 0)
  562.  
  563. foreach (Exam e in exams)
  564.  
  565. {
  566.  
  567. result += e.ToString() + "\n";
  568.  
  569. }
  570.  
  571. //if(listTests.Count !=0)
  572.  
  573. foreach (Test t in listTests)
  574.  
  575. {
  576.  
  577. result += t.ToString() + "\n";
  578.  
  579. }
  580.  
  581. return result;
  582.  
  583. }
  584. //виртуальный метод string ToShortString(), который формирует строку со значениями всех полей класса без списка зачетов и экзаменов, но со значением среднего балл
  585. new public string ToShortString()
  586.  
  587. {
  588.  
  589. string result = base.ToString() + "\n Тип образования: " + education.ToString() + "\n Номер группы: " + numberGroup.ToString() + "\n Средний балл: " + AverageRating.ToString();
  590.  
  591. return result;
  592.  
  593. }
  594.  
  595. public override bool Equals(object obj)
  596.  
  597. {
  598.  
  599. Student student = (Student)obj;
  600.  
  601. bool result = false;
  602.  
  603. if (base.Equals(student))
  604.  
  605. {
  606.  
  607. if (exams.Length == student.exams.Length && listTests.Count == student.listTests.Count)
  608.  
  609. {
  610.  
  611. for (int i = 0; i < exams.Length; i++)
  612.  
  613. {
  614.  
  615. if (exams[i] != student.exams[i])
  616.  
  617. return result;
  618.  
  619. }
  620.  
  621. for (int i = 0; i < listTests.Count; i++)
  622.  
  623. {
  624.  
  625. if (listTests[i] != student.listTests[i])
  626.  
  627. return result;
  628.  
  629. }
  630.  
  631. if (education == student.education)
  632.  
  633. if (numberGroup == student.numberGroup)
  634.  
  635. result = true;
  636.  
  637. }
  638.  
  639. }
  640.  
  641. return result;
  642.  
  643. }
  644.  
  645. public override int GetHashCode()
  646.  
  647. {
  648.  
  649. return ToString().Length;
  650.  
  651. }
  652. //определить перегруженную версию виртуального метода object DeepCopy(
  653. new public object DeepCopy()
  654.  
  655. {
  656.  
  657. Student student = new Student((Person)this, education, numberGroup);
  658.  
  659. for (int i = 0; i < exams.Length; i++)
  660.  
  661. {
  662.  
  663. student.exams[i] = (Exam)exams[i].DeepCopy();
  664.  
  665. }
  666.  
  667. for (int i = 0; i < listTests.Count; i++)
  668.  
  669. {
  670.  
  671. student.listTests[i] = (Test)listTests[i];
  672.  
  673. }
  674.  
  675. return student;
  676.  
  677. }
  678.  
  679. }
  680.  
  681. enum Education
  682.  
  683. {
  684.  
  685. Specialist, Bachelor, SecondEducation
  686.  
  687. }
  688.  
  689. interface IDateAndCopy
  690.  
  691. {
  692.  
  693. object DeepCopy();
  694.  
  695. DateTime Date { get; set; }
  696.  
  697. }
  698.  
  699. class Program
  700.  
  701. {
  702.  
  703. static void Main(string[] args)
  704.  
  705. {
  706. String[] mass = { };
  707. Student student = new Student();
  708.  
  709. //Создать два объекта типа Person с совпадающими данными и проверить, что ссылки на объекты не равны, а объекты равны, вывести значения хэш- кодов для объектов
  710.  
  711. Console.WriteLine("1\n");
  712.  
  713. Person a = new Person();
  714.  
  715. Person b = new Person();
  716.  
  717.  
  718. Console.WriteLine(a.GetHashCode() + " " + b.GetHashCode() + "\n");
  719.  
  720. //Создать объект типа Student, добавить элементы в список экзаменов и
  721.  
  722. //зачетов, вывести данные объекта Student.
  723.  
  724. Console.WriteLine("2\n");
  725.  
  726. Student student2 = new Student();
  727.  
  728. student.AddExam(new Exam("Phisics", 3, new DateTime(2019, 01, 15)));
  729.  
  730. student.AddExam(new Exam("Biology", 4, new DateTime(2019, 01, 10)));
  731.  
  732. student.AddExam(new Exam("Maths", 4, new DateTime(2019, 01, 10)));
  733.  
  734. Array.Resize(ref mass, mass.Length + 1);
  735. mass[mass.Length - 1] = student2.ToString();
  736.  
  737. //#######Console.WriteLine(student2.ToString() + "\n");
  738.  
  739. //Вывести значение свойства типа Person для объекта типа Student.
  740.  
  741. //#######Console.WriteLine("3\n");
  742.  
  743. //#######Console.WriteLine(student2.Person.ToString() + "\n");
  744.  
  745. Array.Resize(ref mass, mass.Length + 1);
  746. mass[mass.Length - 1] = student2.ToString();
  747.  
  748. //С помощью метода DeepCopy() создать полную копию объекта Student.
  749.  
  750. //Изменить данные в исходном объекте Student и вывести копию и исходный
  751.  
  752. // объект, полная копия исходного объекта должна остаться без изменений.
  753.  
  754. Console.WriteLine("4\n");
  755.  
  756. Student student3 = (Student)student2.DeepCopy();
  757.  
  758. student2.Name = "Leys";
  759.  
  760. Array.Resize(ref mass, mass.Length + 1);
  761. mass[mass.Length - 1] = student3.ToString();
  762.  
  763. //######Console.WriteLine(student2.ToString());
  764.  
  765. //######Console.WriteLine(student3.ToString() + "\n");
  766.  
  767. // В блоке try/catch присвоить свойству с номером группы некорректное
  768.  
  769. // значение, в обработчике исключения вывести сообщение, переданное через объект - исключение
  770.  
  771. Console.WriteLine("5\n");
  772.  
  773. try
  774.  
  775. {
  776.  
  777. student.NumberGroup = 90;
  778.  
  779. }
  780.  
  781. catch (Exception e)
  782.  
  783. {
  784.  
  785. Console.WriteLine("\n" + e.Message);
  786.  
  787. }
  788.  
  789. Console.WriteLine();
  790.  
  791. //С помощью оператора foreach вывести список всех зачетов и экзаменов.(С помощью оператора foreach для итератора, определенного в классе Student, вывести список всех зачетов и экзаменов)
  792.  
  793. Console.WriteLine("6\n");
  794.  
  795.  
  796. foreach (Exam e in student.Exams)
  797.  
  798. {
  799.  
  800. Console.WriteLine(e.ToString());
  801.  
  802. }
  803.  
  804. foreach (Test t in student.ListTests)
  805.  
  806. {
  807.  
  808. Console.WriteLine(t.ToString());
  809.  
  810. }
  811.  
  812. //#####Console.WriteLine();
  813.  
  814. //С помощью оператора foreach для итератора с параметром вывести список всех экзаменов с оценкой выше 3.(С помощью оператора foreach для итератора с параметром, определенного в классе Student, вывести список всех экзаменов с оценкой выше 3.)
  815.  
  816. //#####Console.WriteLine("7\n");
  817.  
  818.  
  819. for (int i = 0; i < student.Exams.Length; i++)
  820.  
  821. {
  822.  
  823. if (student.Exams[i].Rating > 3)
  824.  
  825. Console.WriteLine(student.Exams[i].ToString());
  826.  
  827. }
  828.  
  829. // ###########################
  830. // #цикл для перебора массива#
  831. // ###########################
  832.  
  833. Console.WriteLine("Введите оценку...");
  834. int theGrade = Console.Read();
  835.  
  836.  
  837. for (int i = 0; i < student.Exams.Length; i++)
  838.  
  839. {
  840.  
  841. if (student.Exams[i].Rating > theGrade)
  842. {
  843. Console.WriteLine("Студент: " + student.Name+" "+student.LastName+ ", оценка" + student.Exams[i].ToString());
  844. }
  845. }
  846.  
  847.  
  848. foreach (String aMass in mass)
  849. {
  850. Console.WriteLine(aMass);
  851. }
  852.  
  853. Console.ReadKey();
  854.  
  855. }
  856.  
  857. }
  858. }
Advertisement
Add Comment
Please, Sign In to add comment