//Main import java.io.File; import java.io.*; import java.util.Scanner; public class Main { private static final Scanner scan = new Scanner(System.in); static DocumentListMenu DocumentList = new DocumentListMenu(); public static void waitForAction() { System.out.println("Для выхода в меню нажмите Enter..."); scan.nextLine(); } public static void outputProgramInfo() { System.out.println("=======================================================================================================" + "\n" + " Добро пожаловать в программу Хранитель рефератов™!" + "\n" + "Данная программа позволяет хранить основную информацию о рефератах за текущий год. " + "\n" + "Программа дает возможность создать список рефератов и сохранить его в файл со специальном разрешением." + "\n" + "Также представлена возможность производить с записями о рефератах следующие операции:" + "\n" + "- Создание новой записи о реферате; " + "\n" + "- Корректировка записи о реферате;" + "\n" + "- Удаление записи о реферате;" + "\n" + "- Поиск нужных рефератов с помощью фильтров поиска;" + "\n" + " Желаем успешного и приятного пользования программой" + "\n" + " Хранитель рефератов™!" + "\n" + "======================================================================================================="); } public static void outputHelpInfo() { System.out.println("Справка:\n" + "1) Максимальная длина названия темы, фамилии - 20 символов. \n" + "2) Максимальное кол-во страниц реферата - 20. \n" + "3) Дата указывается в формате ДД.ММ.\n" + "4) При загрузке корректриующего файла записи добавляются к уже существующим.\n" + "5) !Важно: при загрузке корректирующего файла список не должен быть пустым"); } public static String inputPathToFile() { boolean isIncorrect; String path; System.out.println("Укажите путь к файлу: "); do { isIncorrect = false; path = scan.nextLine(); File file = new File(path); if (!file.exists()) { System.out.println("По указанному пути файл не найден! Укажите правильный путь: "); isIncorrect = true; } } while (isIncorrect); return path; } public static Document[] inputDocumentsFromFile(String filePath){ final int MIN_PAGES = 1; final int MAX_PAGES = 20; Document[] documents = new Document[0]; String currentString; boolean isIncorrect = false; try (BufferedReader reader = new BufferedReader(new FileReader(filePath)) ) { while((reader.read() != -1) && !(isIncorrect)) { currentString = reader.readLine(); String[] words = currentString.split(" ", 4); String theme = words[0]; String surname = words[1]; int pages = Integer.parseInt(words[2]); String[] dayMonthYear = words[3].split("[.]", 3); int day = Integer.parseInt(dayMonthYear[0].trim()); int month = Integer.parseInt(dayMonthYear[1].trim()); if (surname.length() > 20 || theme.length() > 20 || surname.isEmpty() || pages < MIN_PAGES || pages > MAX_PAGES || theme.isEmpty() || !Date.isCorrectDate(day, month)) { isIncorrect = true; System.out.println("В файле некорректные данные!"); } else { documents = DocumentList.changeCountOfDocuments(documents, documents.length + 1); documents[documents.length - 1] = new Document(theme, surname, pages, new Date(day, month)); } } if (!isIncorrect) { System.out.println("Информация была успешно загружена"); } } catch (Exception e) { System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); } return documents; } public static Document[] AddDocumentsFromFile(String filePath, Document[] documents){ final int MIN_PAGES = 1; final int MAX_PAGES = 20; String currentString; boolean isIncorrect = false; try (BufferedReader reader = new BufferedReader(new FileReader(filePath)) ) { while((reader.read() != -1) && !(isIncorrect)) { currentString = reader.readLine(); String[] words = currentString.split(" ", 4); String theme = words[0]; String surname = words[1]; int pages = Integer.parseInt(words[2]); String[] dayMonthYear = words[3].split("[.]", 3); int day = Integer.parseInt(dayMonthYear[0].trim()); int month = Integer.parseInt(dayMonthYear[1].trim()); if (surname.length() > 20 || theme.length() > 20 || surname.isEmpty() || pages < MIN_PAGES || pages > MAX_PAGES || theme.isEmpty() || !Date.isCorrectDate(day, month)) { isIncorrect = true; System.out.println("В файле некорректные данные!"); } else { documents = DocumentList.changeCountOfDocuments(documents, documents.length + 1); documents[documents.length - 1] = new Document(theme, surname, pages, new Date(day, month)); } } if (!isIncorrect) { System.out.println("Информация была успешно загружена"); } } catch (Exception e) { System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); } return documents; } public static void saveToFile(Document[] documents, String filePath) { try (PrintWriter fileOut = new PrintWriter(filePath)) { for (Document product : documents) fileOut.println(product.getTheme() + " " + product.getSurname() + " " + product.getPages() + " " + product.getDate().getDay() + "." + product.getDate().getMonth() + "." + "2023"); } catch (Exception e) { System.out.println("Произошла ошибка при записи в файл..."); } System.out.println("Данные успешно сохранены в файл!"); } public static int inputIndex(){ final int MIN_INDEX = 1; final int MAX_INDEX = 20; int index = 0; boolean isIncorrect; System.out.println("Введите номер записи"); do { isIncorrect = false; try { index = Integer.parseInt(scan.nextLine()); } catch (Exception e){ System.out.println("Проверьте корректность введенных данных!"); isIncorrect = true; } if (!isIncorrect && (index < MIN_INDEX || index > MAX_INDEX)){ System.out.println("Неверный номер записи!"); isIncorrect = true; } } while (isIncorrect); return index; } public static String inputSurname() { final int MAX_SIZE = 20; String surname; boolean isIncorrect; System.out.println("Введите фамилию автора. Длина не должна превышать 20 букв."); do { isIncorrect = false; surname = scan.nextLine(); if (surname.length() > MAX_SIZE) { isIncorrect = true; System.out.println("Длина не должна превышать 20 букв! Повторите попытку"); } if (surname.isEmpty()) { isIncorrect = true; System.out.println("Введите фамилию!"); } } while (isIncorrect); return surname; } public static String inputTheme() { final int MAX_SIZE = 20; String theme; boolean isIncorrect; System.out.println("Введите название темы. Длина не должна превышать 20 букв."); do { isIncorrect = false; theme = scan.nextLine(); if (theme.length() > MAX_SIZE) { isIncorrect = true; System.out.println("Длина названия темы не должна превышать 20 букв!"); } if (theme.isEmpty()) { isIncorrect = true; System.out.println("Введите название темы!"); } } while (isIncorrect); return theme; } public static Integer inputPages(){ final int MIN_VALUE = 1; final int MAX_VALUE = 20; boolean isIncorrect; int pages = 0; System.out.println("Введите кол-во страниц реферата. Кол-во страниц не должно превышать 20 стр."); do { isIncorrect = false; try { pages = Integer.parseInt(scan.nextLine()); } catch(NumberFormatException e){ System.out.println("Проверьте корректность ввода данных!"); isIncorrect = true; } if (!isIncorrect && (pages < MIN_VALUE || pages > MAX_VALUE)) { System.out.println("Вы ввели некорректное количество!"); isIncorrect = true; } } while (isIncorrect); return pages; } public static Date inputDate(){ boolean isIncorrect; int day = 0; int month = 0; String date; String[] dayMonthYear; System.out.println("Введите дату получения товара. Формат ввода - DD.MM, где DD - день, MM - месяц"); do { isIncorrect = false; date = scan.nextLine(); if (date.isEmpty()) { isIncorrect = true; System.out.println("Введите дату!"); } if (!isIncorrect) { try { dayMonthYear = date.split("[.]", 2); day = Integer.parseInt(dayMonthYear[0].trim()); month = Integer.parseInt(dayMonthYear[1].trim()); if (!Date.isCorrectDate(day, month)){ isIncorrect = true; System.out.println("Вы ввели некорректную дату!"); } } catch (Exception e) { System.out.println("Вы ввели некорректные данные!"); isIncorrect = true; } } } while (isIncorrect); return new Date(day, month); } public static int inputChoice(int menuType) { final int MIN_CHOICE = 1; final int MAX_CHOICE = 10; int choice = 0; boolean isIncorrect; if(menuType == 1){ System.out.println("Меню действий: \n" + "1) Добавить новую запись \n" + "2) Изменить информацию о существующей записи \n" + "3) Удалить существующую запись \n" + "4) Показать весь список записей \n" + "5) Отсортировать список записей по дате \n" + "6) Загрузить файл с записями \n" + "7) Загрузить корректирующий файл \n" + "8) Сохранить список записей в файл \n" + "9) Вызвать справку \n" + "10) Выход из программы \n" + "Выберите одно из действий"); } else { System.out.println("Меню действий: \n" + "1) Изменить название темы\n" + "2) Изменить фамилию автора\n" + "3) Изменить кол-во стр.\n" + "4) Изменить дату написания\n" + "5) Выйти в главное меню\n" + "Выберите одно из действий"); } do { isIncorrect = false; try { choice = Integer.parseInt(scan.nextLine()); } catch (Exception e){ System.out.println("Проверьте корректность введенных данных!"); isIncorrect = true; } if (!isIncorrect && (choice < MIN_CHOICE || choice > MAX_CHOICE)){ System.out.println("Для выбора введите от " + MIN_CHOICE + " до " + MAX_CHOICE + "!"); isIncorrect = true; } } while (isIncorrect); return choice; } public static void choiceMenuOption(int choice) { switch (choice) { case 1 -> { DocumentList.AddDocument(inputSurname(), inputTheme(), inputPages(), inputDate()); System.out.println("Запись была успешно добавлена."); waitForAction(); } case 2 -> { if (DocumentList.getDocuments().length != 0) { System.out.println("Список записей:"); DocumentList.showAllDocuments(); int index = inputIndex() - 1; Document newDocument = DocumentList.getDocuments()[index]; int choiceChangeMenu; do { System.out.println("Выбранная запись:\n" + newDocument.toString()); choiceChangeMenu = inputChoice(2); newDocument = changeMenu(newDocument, choiceChangeMenu); } while (choiceChangeMenu != 5); DocumentList.changeDocument(index, newDocument); } else { System.out.println("На данный момент записей нет..."); waitForAction(); } } case 3 -> { int size = DocumentList.getDocuments().length; if (size != 0) { System.out.println("Список записей:"); DocumentList.showAllDocuments(); DocumentList.deleteDocument(inputIndex() - 1); System.out.println("Запись была успешно удалена"); } else { System.out.println("Записей пока нет..."); } waitForAction(); } case 4 -> { if (DocumentList.getDocuments().length != 0) { System.out.println("Список записей:"); DocumentList.showAllDocuments(); } else { System.out.println("Записей пока нет..."); } waitForAction(); } case 5 -> { if (DocumentList.getDocuments().length != 0) { int i = 0; System.out.println("Отсортированный список записей:\n" + "№ - Тема - Фамилия - Кол-во стр. - Дата написания"); for (Document sortedDocuemtList : DocumentList.sortDocuments()){ System.out.println("[" + (++i) + "]" + sortedDocuemtList.toString()); } } else { System.out.println("Записей пока нет..."); } waitForAction(); } case 6 -> { DocumentList.setDocuments(inputDocumentsFromFile(inputPathToFile())); waitForAction(); } case 7 -> { DocumentList.setDocuments(AddDocumentsFromFile(inputPathToFile(), DocumentList.getDocuments())); waitForAction(); } case 8 -> { if (DocumentList.getDocuments().length != 0) { saveToFile(DocumentList.getDocuments(), inputPathToFile()); } else { System.out.println("Записей пока нет..."); } waitForAction(); } case 9 -> { outputHelpInfo(); waitForAction(); } case 10 -> { System.out.println("Завершение сеанса. Благодарим за использование! Всех благ!"); System.out.println("=======================================================================================================" + "\n" + " Ученье - свет! Неученье - чуть свет и на работу!" + "\n" + " -Хранитель рефератов™!" + "\n" + "======================================================================================================="); ; } } } public static Document changeMenu(Document newDocument, int choice){ switch (choice) { case 1 -> { newDocument.setTheme(inputTheme()); System.out.println("Информация была успешно изменена"); } case 2 -> { newDocument.setSurname(inputSurname()); System.out.println("Информация была успешно изменена"); } case 3 -> { newDocument.setPages(inputPages()); System.out.println("Информация была успешно изменена"); } case 4 -> { newDocument.setDate(inputDate()); System.out.println("Информация была успешно изменена"); } } return newDocument; } public static void main(String[] args) { int choiceForMenu; outputProgramInfo(); do { choiceForMenu = inputChoice(1); choiceMenuOption(choiceForMenu); } while(choiceForMenu != 10); scan.close(); } } ///Document public class Document { private String theme; private String surname; private Integer pages; private Date date; Document(String theme, String surname, Integer pages, Date date) { this.theme = theme; this.surname = surname; this.pages = pages; this.date = date; } public void setTheme(String theme) { this.theme = theme; } public String getTheme() { return this.theme; } public void setSurname(String surname) { this.surname = surname; } public String getSurname() { return surname; } public void setPages(Integer pages) { this.pages = pages; } public Integer getPages() { return pages; } public void setDate(Date date) { this.date = date; } public Date getDate() { return date; } public String toString() { return "[" + theme + "]" + "[" + surname + "]" + "[" + pages.toString() + "]" + "[" + date.toString() + "]"; } } /////DocumentListMenu public class DocumentListMenu { private Document[] documents; DocumentListMenu(){ documents = new Document[0]; } public void AddDocument(String theme, String surname, Integer pages, Date date){ documents = changeCountOfDocuments(documents, documents.length + 1); documents[documents.length - 1] = new Document(theme, surname, pages, date); } public void deleteDocument(int index){ if (index != documents.length - 1){ for (int i = index; i < documents.length - 1; i++){ documents[i] = documents[i + 1]; } } documents = changeCountOfDocuments(documents, documents.length - 1); } public void changeDocument(int index, Document newDocument){ documents[index] = newDocument; } public Document[] sortDocuments(){ Document[] sortedDocuments = new Document[0]; for (int i = 0; i < sortedDocuments.length; i++){ for (int j = 1; j < sortedDocuments.length - i; j++){ if (sortedDocuments[j - 1].getDate().getMonth() > sortedDocuments[j].getDate().getMonth()){ Document tempDoc = sortedDocuments[j - 1]; sortedDocuments[j - 1] = sortedDocuments[j]; sortedDocuments[j] = tempDoc; } else if (sortedDocuments[j - 1].getDate().getDay() > sortedDocuments[j].getDate().getDay()) { Document tempDoc = sortedDocuments[j - 1]; sortedDocuments[j - 1] = sortedDocuments[j]; sortedDocuments[j] = tempDoc; } } } return sortedDocuments; } public void showAllDocuments(){ int i = 0; System.out.println("№ - Тема - Фамилия - Стр. - Дата написания"); for(Document document : documents){ System.out.println("[" + (++i) + "]" + document.toString()); } } public void setDocuments(Document[] documents){ this.documents = documents; } public Document[] getDocuments(){ return documents; } Document[] changeCountOfDocuments(Document[] documents, int newLength){ int size = documents.length; Document[] newDocuments = new Document[newLength]; System.arraycopy(documents, 0, newDocuments, 0, Math.min(newLength, size)); return newDocuments; } } /////DateClass public class Date { private int day; private int month; Date(int day, int month){ this.day = day; this.month = month; } public int getDay(){ return day; } public int getMonth(){ return month; } public static boolean isCorrectDate(int day, int month){ final int MIN_DAY_MONTH = 1; final int MAX_DAY = 31; final int MAX_MONTH = 12; boolean isCorrect; isCorrect = true; if (day < MIN_DAY_MONTH || day > MAX_DAY || month < MIN_DAY_MONTH || month > MAX_MONTH){ isCorrect = false; } else if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) { isCorrect = false; } else if ((month == 2) && (day > 28)) { isCorrect = false; } return isCorrect; } public String toString(){ return day + "/" + month + "/" + "2023 г."; } }