fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. using System.Security;
  8.  
  9. /*Задание для лабораторной работы № 1
  10.  
  11. В соответствии с вариантом задания самостоятельно разработать класс и программу,
  12.   иллюстрирующую его возможности. Требования к классу:
  13. - обязательно наличие закрытой (private) и общедоступной (public) частей;
  14. - класс должен иметь по крайней мере два конструктора, определенных программистом:
  15.   конструктор по умолчанию и конструктор c параметрами;
  16. - необходимо задать набор свойств для получения значений и модификации полей данных,
  17.   находящихся в закрытой части класса;
  18. - для разработанного класса должна быть перегружена одна операция: арифметическая,
  19.   сравнения, присваивания. Выбор перегружаемых операций определяется семантикой предметной области.
  20.  
  21.  # организация
  22.  */
  23.  
  24. /*Задание для лабораторной работы № 2
  25.  
  26. Построить иерархию классов в соответствии с вариантом задания.
  27. В качестве базового абстрактного класса взять класс разработанный Вами в лабораторной работе № 1.
  28. В базовый класс добавить абстрактный метод и реализовать его в производных классах.
  29. Другие методы базового класса сделать виртуальными и переопределить их в классах-наследниках.
  30. Производные классы должны иметь собственные поля данных, отличные от полей базового класса.
  31. Для разработанной Вами иерархии классов в методе Main:
  32. 1) описать массив объектов базового класса;
  33. 2) занести в этот массив из файла(!) объекты дочерних классов;
  34. 3) продемонстрировать работу методов класса у всех элементов этого массива.
  35.  
  36. #5 Организация, страховая компания, нефтегазовая компания, завод
  37.  */
  38.  
  39. /*Задание для лабораторной работы № 3
  40.  
  41. 1. В код лабораторной работы № 2 добавить обработку исключений
  42. «файл не найден», «нет прав доступа к файлу»;
  43. 2. Создать пользовательское исключение согласно Вашей предметной области.
  44. Написать метод, генерирующий пользовательское исключение и обработать его.
  45. */
  46.  
  47. namespace Sem1Lab3
  48. {
  49. abstract class organisation
  50. {
  51. public string OrgName; //название
  52. private int NumOfPeople; //количество людей, работающих там
  53. private int YearsOld; // сколько лет организация существует
  54. private string CompanyType; //тип компании
  55. public abstract void DoWork(); //слыш работать
  56.  
  57. public virtual string Info() //для вывода информации
  58. {
  59. string s = "Organisation info:\n\n" + "Name:" + OrgName + "\nNumber of People:" + NumOfPeople + "\nOrganisation age:" + YearsOld + "\n";
  60. return s;
  61. }
  62.  
  63.  
  64.  
  65. public virtual int InsuranceOrders1
  66. {
  67. get;
  68. set;
  69. }
  70.  
  71. public virtual string MainMiningLocations1
  72. {
  73. get;
  74. set;
  75. }
  76.  
  77. public virtual string FactoryLocation1
  78. {
  79. get;
  80. set;
  81. }
  82.  
  83. public int YearsOld1
  84. {
  85. get { return YearsOld; }
  86. set { YearsOld = value; }
  87. }
  88.  
  89. public int NumOfPeople1
  90. {
  91. get { return NumOfPeople; }
  92. set
  93. {
  94. if (value <= 0)
  95. {
  96. throw new NumberOfPeopleException();
  97. }
  98. else { NumOfPeople = value; }
  99. }
  100. }
  101.  
  102. public string CompanyType1
  103. {
  104. get { return CompanyType; }
  105. set { CompanyType = value; }
  106. }
  107.  
  108. public organisation()
  109. {
  110. OrgName = "Placeholder";
  111. NumOfPeople = 1;
  112. YearsOld = 1;
  113. }
  114.  
  115. public organisation(string OrgName, int NumOfPeople, int YearsOld)
  116. {
  117. this.OrgName = OrgName;
  118. this.NumOfPeople = NumOfPeople;
  119. this.YearsOld = YearsOld;
  120. }
  121.  
  122. public static bool operator >(organisation n1, organisation n2) //оператор сравнивает количество рабочих
  123. {
  124. if (n1.NumOfPeople > n2.NumOfPeople)
  125. return true;
  126. else
  127. return false;
  128. }
  129. public static bool operator <(organisation n1, organisation n2)
  130. {
  131. if (n1.NumOfPeople < n2.NumOfPeople)
  132. return true;
  133. else
  134. return false;
  135. }
  136.  
  137.  
  138.  
  139. }
  140.  
  141. public class NumberOfPeopleException : Exception
  142. {
  143. public NumberOfPeopleException()
  144. {
  145. }
  146.  
  147. public NumberOfPeopleException(string message)
  148. : base(message)
  149. {
  150. }
  151.  
  152. public NumberOfPeopleException(string message, Exception inner)
  153. : base(message, inner)
  154. {
  155. }
  156.  
  157. }
  158.  
  159. class InsuranceCompany : organisation
  160. { //Класс страховая компания
  161. private int InsuranceOrders; //количество заказов на стаховку (я понятия не имею, как работают страховые компании)
  162.  
  163. public override string Info()
  164. {
  165. return base.Info() + "Number of Insurance Orders:" + InsuranceOrders + "\n";
  166. }
  167.  
  168. public override int InsuranceOrders1
  169. {
  170. get { return InsuranceOrders; }
  171. set { InsuranceOrders = value; }
  172. }
  173.  
  174. public InsuranceCompany()
  175. {
  176. InsuranceOrders = 1;
  177. }
  178.  
  179. public override void DoWork()
  180. {
  181. Console.WriteLine("People may leave their orders so Insurance Company can view them and do something I guess, dunno");
  182. }
  183.  
  184. public InsuranceCompany(int InsuranceOrders, string OrgName, int NumOfPeople, int YearsOld)
  185. : base(OrgName, NumOfPeople, YearsOld)
  186. {
  187. this.InsuranceOrders = InsuranceOrders;
  188. }
  189. }
  190.  
  191.  
  192. class OilGasCompany : organisation
  193. { //нефтегаз
  194. private string MainMiningLocations; //основные место добычи
  195.  
  196. public override string Info()
  197. {
  198. return base.Info() + "Main locations for Mining:" + MainMiningLocations + "\n";
  199. }
  200.  
  201. public override string MainMiningLocations1
  202. {
  203. get { return MainMiningLocations; }
  204. set { MainMiningLocations = value; }
  205. }
  206.  
  207. public OilGasCompany()
  208. {
  209. MainMiningLocations = "Iraq";
  210. }
  211.  
  212. public override void DoWork()
  213. {
  214. Console.WriteLine("These are the main locations this company uses to mine Oil and Gas"); //если честно, не знаю, подходит ли слово
  215. } //"mine" для описания добычи газа и нефти
  216.  
  217. public OilGasCompany(string MainMiningLocations, string OrgName, int NumOfPeople, int YearsOld)
  218. : base(OrgName, NumOfPeople, YearsOld)
  219. {
  220. this.MainMiningLocations = MainMiningLocations;
  221. }
  222.  
  223. }
  224.  
  225. class Factory : OilGasCompany
  226. {
  227. private string FactoryLocation; //местоположение завода
  228.  
  229. public override string Info()
  230. {
  231. return base.Info() + "Factory Location:" + FactoryLocation + "\n";
  232. }
  233.  
  234. public Factory(string FactoryLocation, string MainMiningLocations, string OrgName, int NumOfPeople, int YearsOld)
  235. : base(MainMiningLocations, OrgName, NumOfPeople, YearsOld)
  236. {
  237. this.FactoryLocation = FactoryLocation;
  238. }
  239.  
  240. public override string MainMiningLocations1
  241. {
  242. get
  243. {
  244. return base.MainMiningLocations1;
  245. }
  246.  
  247. set
  248. {
  249. base.MainMiningLocations1 = value + ", " + FactoryLocation1;
  250. }
  251. }
  252.  
  253. public override string FactoryLocation1
  254. {
  255. get { return FactoryLocation; }
  256. set { FactoryLocation = value; }
  257. }
  258.  
  259. public Factory()
  260. {
  261. FactoryLocation = "Syria";
  262. }
  263.  
  264. public override void DoWork()
  265. {
  266. Console.WriteLine("Location of our main and biggest Oil and Gas distilling Factory");
  267. }
  268. }
  269.  
  270.  
  271. class Program
  272. {
  273. static void Main()
  274. {
  275.  
  276. string inputFile;
  277. Console.WriteLine("File name:");
  278. inputFile = Console.ReadLine();
  279. try
  280. {
  281. StreamReader sr = new StreamReader(inputFile);
  282.  
  283. string inLine;
  284. string[] arguments;
  285. int N;
  286. N = Int32.Parse(sr.ReadLine());
  287. organisation[] kol = new organisation[N];
  288. for (int i = 0; i < N; i++)
  289. {
  290. inLine = sr.ReadLine();
  291. arguments = inLine.Split();
  292. if (arguments[0][0] == 'I')
  293. {
  294. kol[i] = new InsuranceCompany();
  295. kol[i].InsuranceOrders1 = Int32.Parse(arguments[4]);
  296. }
  297. if (arguments[0][0] == 'O')
  298. {
  299. kol[i] = new OilGasCompany();
  300. kol[i].MainMiningLocations1 = arguments[4];
  301. }
  302. if (arguments[0][0] == 'F')
  303. {
  304. kol[i] = new Factory();
  305. kol[i].MainMiningLocations1 = arguments[4];
  306. kol[i].FactoryLocation1 = arguments[4];
  307. }
  308. kol[i].OrgName = arguments[1];
  309. kol[i].NumOfPeople1 = Int32.Parse(arguments[2]);
  310. kol[i].YearsOld1 = Int32.Parse(arguments[3]);
  311. }
  312. foreach (organisation elem in kol)
  313. {
  314. Console.WriteLine(elem.Info());
  315. elem.DoWork();
  316. Console.WriteLine();
  317.  
  318. }
  319. }
  320. catch (FileNotFoundException)
  321. {
  322. Console.WriteLine("File Not Found");
  323. }
  324. catch (SecurityException)
  325. {
  326. Console.WriteLine("You have no Permission to open this file");
  327. }
  328. catch (NumberOfPeopleException)
  329. {
  330. Console.WriteLine("Company must have people working in it!");
  331. }
  332.  
  333.  
  334. }
  335.  
  336.  
  337. }
  338.  
  339.  
  340. }
Runtime error #stdin #stdout #stderr 0.03s 14316KB
stdin
Standard input is empty
stdout
File name:
stderr
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: path
  at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize, System.Boolean checkHost) [0x00022] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize) [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path, System.Boolean detectEncodingFromByteOrderMarks) [0x0000d] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path) [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0 
  at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string)
  at Sem1Lab3.Program.Main () [0x00010] in <36e0c126b81141aaa19ae5118c545090>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentNullException: Value cannot be null.
Parameter name: path
  at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize, System.Boolean checkHost) [0x00022] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize) [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path, System.Boolean detectEncodingFromByteOrderMarks) [0x0000d] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.IO.StreamReader..ctor (System.String path) [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0 
  at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string)
  at Sem1Lab3.Program.Main () [0x00010] in <36e0c126b81141aaa19ae5118c545090>:0