Форум программистов, компьютерный форум, киберфорум
PascalABC.NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/5: Рейтинг темы: голосов - 5, средняя оценка - 5.00
Alvin Seville
 Аватар для Соколиный глаз
343 / 273 / 134
Регистрация: 25.07.2014
Сообщений: 4,537
Записей в блоге: 22

Почему вылетает с ошибкой NullReferenceException?

19.06.2017, 17:23. Показов 1057. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Код модуля:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
unit GraphOptimized;
 
uses GraphABC;
 
const
  Radius = 5;
 
type
  ///Location object
  Location = class
  private 
    dx, dy: integer;
    
    function XpositionRead()  := dx;
    
    function YpositionRead()  := dy;
    
    procedure XpositionWrite(v: integer);
    begin
      dx := v;
    end;
    
    procedure YpositionWrite(v: integer);
    begin
      dy := v;
    end;
  
  public 
    constructor(x, y: integer);
    begin
      dx := x;dy := y;
    end;
    
    ///X
    property Xposition: integer read XpositionRead write XpositionWrite;
    ///Y
    property Yposition: integer read YpositionRead write YpositionWrite;
  end;
  
  
  ///Graph's vertex
  GraphVertex = class
  private 
    p: Location;
    n: string;
    marked: boolean;
    Lev: integer;
    col: Color;
    function PositionRead()  := p;
    
    procedure PositionWrite(v: Location);
    begin
      p := v;
    end;
    
    function NameRead()  := n;
    
    procedure NameWrite(v: string);
    begin
      n := v;
    end;
    
    function IsMarkedRead()  := marked;
    
    procedure IsMarkedWrite(v: boolean);
    begin
      marked := v;
    end;
    
    function LevelRead()  := Lev;
    
    procedure LevelWrite(v: integer);
    begin
      Lev := v;
    end;
    
    function ColorValueRead()  := col;
    
    procedure ColorValueWrite(v: color);
    begin
      col := v;
    end;
  
  public 
    ///List of linked vertices
    Vertices: List<GraphVertex>;
    
    constructor(x, y: integer);
    begin
      p := new Location(x, y);marked := false;
    end;
    
    ///Position of the vertex
    property Position: Location read PositionRead write PositionWrite;
    ///Vertex'es name
    property Name: string read NameRead write NameWrite;
    ///The vertex is marked
    property IsMarked: boolean read IsMarkedRead write IsMarkedWrite;
    ///Level value (for DFS and other seaching algorithms)
    property Level: integer read LevelRead write LevelWrite;
    ///Color of the vertex
    property ColorValue: color read ColorValueRead write ColorValueWrite;
    
    ///Draw free vertex
    procedure Draw(v: GraphVertex);
    begin
      SetPenColor(clBlack);
      SetPenWidth(1);
      SetBrushColor(ColorValue);
      FillCircle(v.Position.Xposition, v.Position.Yposition, Radius);
      DrawCircle(v.Position.Xposition, v.Position.Yposition, Radius);
      SetBrushColor(ARGB(0, 0, 0, 0));
      if IsMarked then
        TextOut(v.Position.Xposition + 10, v.Position.Yposition + 10, v.Name + ' X [' + IntToStr(Lev) + ']')
      else
        TextOut(v.Position.Xposition + 10, v.Position.Yposition + 10, v.Name + ' [' + IntToStr(Lev) + ']');
    end;
    
    ///Draw all vertices, those are liked to the current vertex.
    procedure DrawLinked();
    begin
      for var i := 0 to Vertices.Count - 1 do Draw(Vertices.Item[i]);
    end;
    
    ///Draw vertex
    procedure DrawSelf() := Draw(self);
    
    ///Draw all lines those connect the current vertex to the others
    procedure DrawLines();
    begin
      Draw(self);
      for var i := 0 to Vertices.Count - 1 do
        if Vertices.Item[i] <> nil then
          Line(Position.Xposition, Position.Yposition, Vertices.Item[i].Position.Xposition, Vertices.Item[i].Position.Yposition);
    end;
    
    ///Add new vertex
    procedure AddVertex(v: GraphVertex):=Vertices.Add(v);
    
    ///Link two vertices
    procedure LinkTwoVertices(v: GraphVertex);
    begin
      AddVertex(v);
      v.AddVertex(self);
    end;
    
    ///Add new vertex in any array
    class procedure AddVertex(var a: array of GraphVertex; v: GraphVertex);
    begin
      SetLength(a, Length(a) + 1);
      a[Length(a) - 1] := v;
    end;
    
    ///Replace the first vertex with the second one
    procedure ResetVertex(v, v2: GraphVertex);
    var
      l, i: integer;
    begin
      l := Vertices.Count;
      i := 0;
      while (i < l) and (Vertices.Item[i] <> v) do Inc(i);
      Vertices.Item[i] := v2;
    end;
    
    ///Replace the first vertex with the second one in any array
    procedure ResetVertex(var a: array of GraphVertex; v, v2: GraphVertex);
    var
      l, i: integer;
    begin
      l := Length(a);
      i := 0;
      while (i < l) and (a[i] <> v) do Inc(i);
      a[i] := v2;
    end;
    
    ///Get vertex by it's id (name).
    class function GetVertex(a: array of GraphVertex; id: string): GraphVertex;
    var
      l, i: integer;
    begin
      l := Length(a);
      i := 0;
      while (i < l) and (a[i].Name <> id) do Inc(i);
      if i < l then GetVertex := a[i] else GetVertex := nil;
    end;
    
    ///Get vertex by it's level (vL).
    class function GetVertex(a: array of GraphVertex; vL: integer): GraphVertex;
    var
      l, i: integer;
    begin
      l := Length(a);
      i := 0;
      while (i < l) and (a[i].Level <> vL) do Inc(i);
      if i < l then GetVertex := a[i] else GetVertex := nil;
    end;
    
    ///Get all marked (not marked) vertexes from Vertexes.
    function GetMarkedVertexes(t: boolean): array of GraphVertex;
    var
      a: array of GraphVertex;
    begin
      for var i := 0 to Vertices.Count - 1 do
        if Vertices.Item[i].IsMarked = t then AddVertex(a, Vertices.Item[i]);
      GetMarkedVertexes := a;
    end;
  end;
end.
Код программы, рисующей граф и обрабатывающей его по алгоритму DFS:
Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
uses crt, BaseInterpolations, GraphOptimized, GraphABC;
const
  n = 8;
 
var
  a, b: array of GraphOptimized.GraphVertex;
  q: Stack<GraphOptimized.GraphVertex>;
  CurrVert: GraphOptimized.GraphVertex;
  LinkedVerts: array of GraphOptimized.GraphVertex;
 
///Получить вершину по имени.
function Get(name: string):= GraphOptimized.GraphVertex.GetVertex(a, name);
 
begin
  SetLength(a, n);
  for var i := 0 to n - 1 do begin a[i] := new GraphVertex(0, 0);a[i].ColorValue := RGB(255, 0, 0); end;
  
  a[0].Name := 'A';a[1].Name := 'B';a[2].Name := 'C';
  a[3].Name := 'D';a[4].Name := 'E';a[5].Name := 'F';
  a[6].Name := 'H';a[7].Name := 'K';
  
  Get('A').Position.Xposition := 200;Get('A').Position.Yposition := 100;
  Get('B').Position.Xposition := 400;Get('B').Position.Yposition := 100;
  Get('C').Position.Xposition := 500;Get('C').Position.Yposition := 400;
  Get('D').Position.Xposition := 600;Get('D').Position.Yposition := 300;
  Get('F').Position.Xposition := 700;Get('F').Position.Yposition := 400;
  Get('E').Position.Xposition := 400;Get('E').Position.Yposition := 500;
  Get('H').Position.Xposition := 100;Get('H').Position.Yposition := 400;
  Get('K').Position.Xposition := 300;Get('K').Position.Yposition := 400;
  
  Get('A').LinkTwoVertices(Get('B')); Get('A').LinkTwoVertices(Get('K')); Get('A').LinkTwoVertices(Get('H')); //Ошибка в этой строке происходит.
  Get('H').LinkTwoVertices(Get('K'));
  Get('B').LinkTwoVertices(Get('C'));
  Get('C').LinkTwoVertices(Get('D'));
  Get('C').LinkTwoVertices(Get('E'));
  Get('D').LinkTwoVertices(Get('F'));
  
  q := new Stack<GraphVertex>();
  q.Push(Get('A'));
  
  while (q.Count <> 0) and (CurrVert <> nil) and (CurrVert.Name <> 'C') do
  begin
    CurrVert := q.Pop;
    CurrVert.IsMarked := true;
    LinkedVerts := CurrVert.GetMarkedVertexes(false);
    for var i := 0 to Length(LinkedVerts) - 1 do
    begin
      LinkedVerts[i].Level := CurrVert.Level + 1;
      q.Push(LinkedVerts[i]);
    end;
  end;
  
  for var i := 0 to n - 1 do
  begin
    a[i].DrawSelf;a[i].DrawLines;
  end;
end.
В чем причина?

Добавлено через 1 минуту
Unhandled Exception: System.NullReferenceException: Ссылка на объект не указывает на экземпляр объекта.
в GraphOptimized.GraphVertex.AddVertex(Gra phVertex v) в C:\Ilya\GraphOptimized.pas:строка 138
в GraphOptimized.GraphVertex.LinkTwoVertic es(GraphVertex v) в C:\Ilya\GraphOptimized.pas:строка 143
в Verts DFS.Program.$Main() в C:\Ilya\Verts DFS.pas:строка 31
в Verts DFS.Program.Main()Программа завершена, нажмите любую клавишу . . .
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
19.06.2017, 17:23
Ответы с готовыми решениями:

Почему вылетает с ошибкой NullReferenceException при закраске пикселя?
uses crt,GraphABC; type Point2D = class X, Y: real; constructor(px, py: real); begin X := px;Y :=...

Почему вылетает System.NullReferenceException?
Привет народ ) есть класс using MaxAll.Facebooks; using MaxAll.View; using System.Threading; using System.Windows; using...

Программа вылетает с ошибкой EXC_? (11). Почему?
Комрады, надеюсь на вашу помощь. Решил тряхнуть стариной (лет 13 назад в вузе изучал делфи) и попробовать написать игрушку для дочки на...

1
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33393 / 21503 / 8236
Регистрация: 22.10.2011
Сообщений: 36,899
Записей в блоге: 12
19.06.2017, 17:31
Vertices кто создавать будет?

Pascal
84
85
86
  public 
    ///List of linked vertices
    Vertices := new List<GraphVertex>;
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
19.06.2017, 17:31
Помогаю со студенческими работами здесь

Почему вылетает с ошибкой, а не создает два
Почему вылетает с ошибкой? На VBA модуль переписывал с Pascal-евского оригинального варианта (моего). Немного о модуле: Модуль...

При работе программы вылетает исключение NullReferenceException
Добрый вечер, при работе программы выливает исключение на строчки вот само исключение //Copy rights are reserved for Akram kamal...

Пост на строне сервера выполняется, а на стороне кода вылетает NullReferenceException
Привет. У меня возникла проблема при работе с xNet HttpRequest. В общем, у меня есть класс в котором я выполняю логин на портал, в этом...

Access вылетает с ошибкой
При двойном нажатии на некоторые поля в списке, аксесс крашится

ILMerge вылетает с ошибкой
Написал программу, использующую пару библиотек из Nuget. В итоге в папке Debug получились файлы ddl, xml, один exe, один pdb, один...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Символьное дифференцирование
igorrr37 13.02.2026
/ * Программа принимает математическое выражение в виде строки и выдаёт его производную в виде строки и вычисляет значение производной при заданном х Логарифм записывается как: (x-2)log(x^2+2) -. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
Установка Qt-версии Lazarus IDE в Debian Trixie Xfce
volvo 10.02.2026
В общем, достали меня глюки IDE Лазаруса, собранной с использованием набора виджетов Gtk2 (конкретно: если набирать текст в редакторе и вызвать подсказку через Ctrl+Space, то после закрытия окошка. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru