Файл: Разработка объектной программы для обработки данных о авторах издательства.docx

ВУЗ: Не указан

Категория: Курсовая работа

Дисциплина: Не указана

Добавлен: 18.03.2024

Просмотров: 119

Скачиваний: 3

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.


end

else

ShowMessage('Нечего удалять');

UpdateBtnState();

end;
procedure TForm1.ButtonDeleteBookClick(Sender: TObject);

var

aName: string;

author: TAuthor;

begin

// удялаем - выбранный в таблице элемент

aName := StringGridBooks.Cells[0, StringGridBooks.Row];

author := SelectedAuthor();

if ((author <> nil) and (not aName.IsEmpty)) then

begin

if not author.Delete(aName) then

ShowMessage('Ошибка удаления');

LoadAuthors();

LoadBooks(author);

end;

UpdateBtnState();

end;
procedure TForm1.EditAuthorNameUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char);

begin

case UTF8Key of

'A'..'Z', 'a'..'z', 'а'..'я', 'А'..'Я', #8, #32: ;

else

UTF8Key := #0;

end;

end;
procedure TForm1.EditCirculationKeyPress(Sender: TObject; var Key: char);

begin

if not CharInSet(Key, ['0' .. '9', #8]) then

Key := #0;

end;
procedure TForm1.EditBookNameUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char);

begin

case UTF8Key of

'A'..'Z', 'a'..'z', 'а'..'я', 'А'..'Я','0'..'9', #8, #32: ;

else

UTF8Key := #0;

end;

end;
procedure TForm1.LoadAuthors();

var

item: TAuthor;

i: integer;

begin

ClearGrid(StringGridAuthors);
for i := 0 to aPublishing.GetAuthorCount - 1 do// проходим по всем авторам

begin

item := aPublishing.GetAuthor(i);

StringGridAuthors.Cells[0, i + 1] := item.GetAuthorName();

StringGridAuthors.Cells[1, i + 1] := item.GetBooksCount.ToString;

StringGridAuthors.Cells[2, i + 1] := item.SumCirculation.ToString;

end;
LoadBooks(SelectedAuthor); // загружаем связные данные
end;
procedure TForm1.StringGridAuthorsClick(Sender: TObject);

var

author: TAuthor;

begin

author := SelectedAuthor;

LoadBooks(author);

UpdateBtnState();

end;
procedure TForm1.StringGridBooksClick(Sender: TObject);

begin

UpdateBtnState();

end;
procedure TForm1.LoadBooks(aAuthor: TAuthor);

var

temp: TBook;

index: integer;

begin

ClearGrid(StringGridBooks);
if (aAuthor = nil) then

exit;

if StringGridBooks.RowCount - 1 < aAuthor.GetBooksCount then

begin

StringGridBooks.RowCount := StringGridBooks.FixedRows + aAuthor.GetBooksCount; //устанавливаем колиество строк

end;
index := 1;

temp := aAuthor.GetHead().GetNext;

while (temp <> nil) do

begin

StringGridBooks.Cells[0, index] := temp.GetBookName;

StringGridBooks.Cells[1, index] := temp.GetCirculation.ToString;

Inc(index);

temp := temp.GetNext;

end;

ObTirag.Text:=IntToStr(aPublishing.GetObTirag);

end;
function TForm1.SelectedAuthor: TAuthor;

begin

Result := nil;

if (StringGridAuthors.Row > 0) then

if (StringGridAuthors.Row <= aPublishing.GetAuthorCount) then

Result := aPublishing.GetAuthor(StringGridAuthors.Row - 1);

end;
procedure TForm1.UpdateBtnState();

var aAuthor : TAuthor; selectedBook:string;

begin

aAuthor:= SelectedAuthor;

selectedBook := StringGridBooks.Cells[0, StringGridBooks.Row];

ButtonDeleteAuthor.Enabled:= aPublishing.GetAuthorCount > 0;

ButtonAddFirstBook.Enabled := (aAuthor <> nil) and (aAuthor.GetBooksCount = 0);

ButtonAddBookAfter.Enabled := (aAuthor <> nil) and (not selectedBook.IsEmpty) and (aAuthor.GetBooksCount > 0);

ButtonAddBookBefore.Enabled := (aAuthor <> nil) and (not selectedBook.IsEmpty) and (aAuthor.GetBooksCount > 0);

ButtonDeleteBook.Enabled := (aAuthor <> nil) and (not selectedBook.IsEmpty) and (aAuthor.GetBooksCount > 0);
end;
procedure TForm1.ClearGrid(aStringGrid: TStringGrid);

var

i: integer;

j: integer;

begin

for i := 0 to aStringGrid.ColCount - 1 do

for j := 1 to aStringGrid.RowCount - 1 do

aStringGrid.Cells[i, j] := '';

end;
end.

unit unitPublishing;
interface
uses

Classes, unitAuthor, unitBook;
type
TPublishing = class // класс издетальство


private

AuthorCount: integer; // количество авторов

AuthorList: array of TAuthor; // динамичесий массив

ObTirag:integer;

public

constructor Create(aSize: integer);

function GetAuthorCount(): integer; // чтение количества авторов

function GetObTirag:integer; // подсчёт общего тиража издательства

procedure AddAuthor(aAuthor: TAuthor);// добавление автора

function DeleteAuthor(): boolean; // удаление автора

function GetAuthor(index: integer): TAuthor; // получает автора по номеру в очереди

function SumCirculation: integer; // суммарный тираж

procedure Save(Filename: string); // сохранение структуры в файл

procedure Load(Filename: string); // загрузка структуры из файла

end;
implementation
constructor TPublishing.Create(aSize: integer);

begin

AuthorCount := 0;

SetLength(AuthorList, aSize); // устанавливаем изначальную размерность массива

end;
function TPublishing.GetAuthorCount(): integer;

begin

Result := AuthorCount;

end;
function TPublishing.GetObTirag:integer;

Var i:integer;

begin

ObTirag:=0;

if AuthorCount=0 then

result:=0

else

begin

for i:= 0 to AuthorCount-1 do

begin

ObTirag:=ObTirag+ AuthorList[i].SumCirculation;

end;

result:=ObTirag;

end;

end;
procedure TPublishing.AddAuthor(aAuthor: TAuthor);

begin

if (AuthorCount = Length(AuthorList)) then // если мест нет, увеличиваем размер массива

begin

SetLength(AuthorList, Length(AuthorList) * 2);

end;

AuthorList[AuthorCount] := aAuthor;// добавляем в конец массива новый элемент

Inc(AuthorCount); // увеличиваем счётчик числа элементов

end;
function TPublishing.DeleteAuthor(): boolean;

var

i: integer;

begin

Result := False;

if (AuthorCount > 0) then

begin

for i := 0 to AuthorCount - 2 do

AuthorList[i] := AuthorList[i + 1]; // перемещает ячейки на одну влево

Dec(AuthorCount); // уменьшаем счётчик числа элементов

Result := True;

end;

end;
function TPublishing.GetAuthor(index: integer): TAuthor;

begin

Result := AuthorList[index];

end;
function TPublishing.SumCirculation: integer;

var

i: integer;

begin

Result := 0;

for i := 0 to AuthorCount - 1 do

begin

Result := Result + AuthorList[i].SumCirculation;

end;

end;
procedure TPublishing.Save(Filename: string);

var

f: Textfile;

author: TAuthor;

book: TBook;

i: integer;


begin

Assign(f, Filename); // соединяем файл с переменной

rewrite(f); // Открываем файл на запись

for i := 0 to AuthorCount - 1 do // проходим по всем авторам

begin

author := AuthorList[i];

writeln(f, author.GetAuthorName); // запись фамилии автора

writeln(f, author.GetBooksCount); // запись количества книг

book := author.GetHead.GetNext;

while (book <> nil) do// проходим по всем книгам

begin

writeln(f, book.GetBookName); // запись названия книги

writeln(f, book.GetCirculation); // запись тиража
book := book.GetNext; // переходим к след элементу

end;

end;

CloseFile(f);

end;
procedure TPublishing.Load(Filename: string);

var

aFile: Textfile;

author: TAuthor; // экземпляр автора

tauthorCount: integer; // количество авторов

aAuthorName: string; // фамилия автора

i: integer;

book: TBook; // экземпляр книги

aBookName: string; // название книги

aCirculation: integer; // тираж

lastBook: TBook; // закладка - ссылка на посл добавленную книгу

begin

AssignFile(aFile, Filename);

reset(aFile);

while not EOF(aFile) do

begin

lastBook := nil;

Readln(aFile, aAuthorName); // фамилия автора

author := TAuthor.Create(aAuthorName); // создаём автора

Readln(aFile, tauthorCount); // считываем количество авторов

for i := 1 to tauthorCount do

begin

Readln(aFile, aBookName); // считываем название книги

Readln(aFile, aCirculation); // считываем тираж

book := TBook.Create(aBookName, aCirculation);// создаём книгу

if author.GetBooksCount = 0 then

author.AddFirst(book) // добавляем первую книгу

else

author.AddAfter(book, lastBook.GetBookName); // добавляем в конец

lastBook := book; // сохраняем последнюю добавленную книгу

end;

AddAuthor(author); // добавляем автора в издательство

end;

CloseFile(aFile);

end;

unit unitAuthor;
interface
uses

Classes, uniTBook;
type

TAuthor = class // класс автор

private

AuthorName: string; // фамилия автора

BooksCount: integer; // количество книг

Head: TBook; // ссылка на заголовок

public

constructor Create(aAuthorName: string);

function GetAuthorName(): string;

function GetBooksCount(): integer;

function GetHead(): TBook;

procedure SetAuthorName(aAuthorName: string);

procedure AddFirst(aBook: TBook); // добавляет в начало

function AddAfter(aBook: TBook; aBookName: string): boolean; // добавление после заданного

function AddBefore(aBook: TBook; aBookName: string): boolean; // добавление перед заданным

function Delete(aBookName: string): boolean; // удаление

function Search(aLastName: string): TBook; overload; // поиск обычный

function Search(aLastName: string; var pPrev: TBook): TBook; overload; // поиск с возвратом предшетсвенника


function SumCirculation: integer; // суммарный тираж

end;
implementation
constructor TAuthor.Create(aAuthorName: string);

begin

AuthorName := aAuthorName;

Head := TBook.Create('', 0); // создаём заголовок

BooksCount := 0;

end;
function TAuthor.GetAuthorName(): string;

begin

Result := AuthorName;

end;
procedure TAuthor.SetAuthorName(aAuthorName: string);

begin

AuthorName := aAuthorName;

end;
function TAuthor.GetBooksCount(): integer;

begin

Result := BooksCount;

end;
function TAuthor.GetHead(): TBook;

begin

Result := Head;

end;
procedure TAuthor.AddFirst(aBook: TBook);

begin

begin

Head.SetNext(aBook); // Изменяеем ссылку на след у заголовка на новый

BooksCount := BooksCount + 1;

end;

end;
function TAuthor.AddAfter(aBook: TBook; aBookName: string): boolean;

var

temp: TBook;

begin

Result := False;

temp := Search(aBookName); // поиск книги

if (temp <> nil) then // при её нахождении

begin

aBook.SetNext(temp.GetNext);// настриваем ссылки

temp.SetNext(aBook);

BooksCount := BooksCount + 1; // увеличиваем счетчик

Result := True;

end;

end;
function TAuthor.AddBefore(aBook: TBook; aBookName: string): boolean;

var

temp, prev: TBook;

begin

Result := False;

temp := Search(aBookName, prev); // поиск книги и её предшественника

if (temp <> nil) then // при её нахождении

begin

aBook.SetNext(prev.GetNext); // настриваем ссылки

prev.SetNext(aBook);

BooksCount := BooksCount + 1; // увеличиваем счетчик

Result := True;

end;

end;
function TAuthor.Delete(aBookName: string): boolean;

var

temp, prev: TBook;

begin

Result := False;

temp := Search(aBookName, prev); // поиск книги и её предшественника

if (prev <> nil) then // при нахождении

begin

prev.SetNext(temp.GetNext);// настриваем ссылки

temp := nil;

BooksCount := BooksCount - 1;// увеличиваем счётчик

Result := True;

end;

end;
function TAuthor.Search(aLastName: string): TBook;

var

temp: TBook;

begin

Result := nil;

temp := Head.GetNext; // установка переменной в начало списка

while temp <> nil do // организация цикла до достижения заголовка

if temp.GetBookName = aLastName then// в случае нахождения прерывание

begin

Result := temp;

break;

end

else

temp := temp.GetNext;// переход к следующему

end;
function TAuthor.Search(aLastName: string; var pPrev: TBook): TBook;

var

temp: TBook;

begin

Result := nil;

pPrev := Head;

temp := Head.GetNext;// установка переменной в начало списка

while (temp <> nil) do // организация цикла до достижения заголовка

begin

if (aLastName = temp.GetBookName) then // в случае нахождения прерывание

begin

Result := temp;

break;

end

else

begin

pPrev := temp; // Запомнимаем предыдущего

temp := temp.GetNext;// переходим к следующему

end;

end;

end;
function TAuthor.SumCirculation: integer;

var

temp: TBook;

begin

Result := 0;

temp := Head.GetNext;

while (temp <> nil) do

begin

Result := Result + temp.GetCirculation;

temp := temp.GetNext;


end;

end;
end.

unit unitBook;
interface
uses

Classes;
type

TBook = class // класс книга

private

BookName: string; // название книги

Circulation: integer; // тираж

Next: TBook; // след книга

public

constructor Create(aBookName: string; aCirculation: integer);

function GetNext: TBook;

function GetBookName: string;

function GetCirculation: integer;

procedure SetNext(aNext: TBook);

procedure SetBookName(aBookName: string);

procedure SetCirculation(aCirculation: integer);

end;
implementation
constructor TBook.Create(aBookName: string; aCirculation: integer);

begin

BookName := aBookName;

Circulation := aCirculation;

end;
function TBook.GetNext: TBook;

begin

Result := Next;

end;
procedure TBook.SetNext(aNext: TBook);

begin

Next := aNext;

end;
function TBook.GetBookName: string;

begin

Result := BookName;

end;
procedure TBook.SetBookName(aBookName: string);

begin

BookName := aBookName;

end;
function TBook.GetCirculation: integer;

begin

Result := Circulation;

end;
procedure TBook.SetCirculation(aCirculation: integer);

begin

Circulation := aCirculation;

end;
end.