При попытке заполнить поле класса выбрасывается исключение "System.NullReferenceException" - C#
Формулировка задачи:
При попытке заполнить поле класса выбрасывает исключение "System.NullReferenceException"
обвиняет эту строку
да, тут массив объектов.
Тут я реализую задачу Джонсона для двух станков. Если есть еще решения на С# то тоже можно скинуть, буду благодарен.
Код программы если он необходим.
Листинг программы
- AData[i].A = int.Parse(Console.ReadLine());
Листинг программы
- using System;
- namespace algoritmJohnsona
- {
- class Items
- {
- public static int a, b, id;
- public int result;
- public static bool operator <(Items Obj1, Items Obj2)
- {
- if (Obj1.result < Obj2.result)
- return true;
- return false;
- }
- public static bool operator >(Items Obj1, Items Obj2)
- {
- if (Obj1.result > Obj2.result)
- return true;
- return false;
- }
- public void Difference()
- {
- result = a - b;
- }
- public int ID
- {
- get
- {
- return id;
- }
- set
- {
- id = value;
- }
- }
- public int A
- {
- set
- {
- a = value;
- }
- }
- public int B
- {
- set
- {
- b = value;
- }
- }
- }
- class Program
- {
- public static void ShowItems(Items[] ArrayData)
- {
- for (int i = 0; i < ArrayData.Length; i++)
- Console.WriteLine("J = {0}", ArrayData[i].ID);
- }
- public static void SwapItems(Items Obj1, Items Obj2)
- {
- int temp = Obj1.result;
- Obj1.result = Obj2.result;
- Obj2.result = temp;
- }
- public static void SortItems(Items[] ArrayData)
- {
- for (int i = 1; i < ArrayData.Length; i++)
- for (int j = i; j > 0 && ArrayData[j - 1] > ArrayData[j]; j--) // пока j>0 и элемент j-1 > j, x-массив int
- SwapItems(ArrayData[j - 1], ArrayData[j]); // меняем местами элементы j и j-1
- }
- static void Main(string[] args)
- {
- Items[] AData = new Items[5];
- Console.WriteLine("Enter Array");
- for (int i = 0; i < AData.Length;i++ )
- {
- Console.Write(" Pass Y1: ");
- int y = int.Parse(Console.ReadLine());
- Console.WriteLine(y);
- AData[i].A = int.Parse(Console.ReadLine()); // обвиняет эту строку
- Console.Write(" Pass Y2: ");
- AData[i].B = int.Parse(Console.ReadLine());
- AData[i].Difference();
- }
- SortItems(AData);
- ShowItems(AData);
- Console.ReadKey();
- }
- }
- }
Решение задачи: «При попытке заполнить поле класса выбрасывается исключение "System.NullReferenceException"»
textual
Листинг программы
- for (int i = 0; i < AData.Length;i++ )
- {
- AData[i] = new Items();
- AData[i].ID = i;
- Console.Write(" Pass Y1: ");
- AData[i].A = int.Parse(Console.ReadLine());
- Console.Write(" Pass Y2: ");
- AData[i].B = int.Parse(Console.ReadLine());
- AData[i].Difference();
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д