Advertisement
venik2405

lab5_1

Apr 8th, 2021
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.17 KB | None | 0 0
  1. package com.company.starter;
  2.  
  3. import com.company.struct.LinkList;
  4. import com.company.struct.Student;
  5.  
  6. import java.io.*;
  7. import java.util.Scanner;
  8.  
  9. public class Main {
  10.  
  11.     static Scanner scannerConsole;
  12.     static LinkList listInt;
  13.  
  14.     static final int CREATE_LIST = 1;
  15.     static final int OPEN_LIST = 2;
  16.     static final int ADD_ELEMENT = 1;
  17.     static final int DELETE_ELEMENT = 2;
  18.     static final int VIEW_LIST = 3;
  19.     static final int MAIN_TASK = 4;
  20.     static final int SAVE_LIST_OF_MENU = 5;
  21.     static final int OPEN_LIST_OF_MENU = 6;
  22.     static final int EXIT_PROGRAM = 0;
  23.     static final int MIN_INDEX = 1;
  24.     static int date;
  25.     static int coursesCol = 4;
  26.  
  27.     static int enterValue() {
  28.         int num;
  29.         boolean isCorrect = true;
  30.         num = 0;
  31.         do {
  32.             try {
  33.                 num = Integer.parseInt(scannerConsole.nextLine());
  34.                 isCorrect = false;
  35.             } catch (Exception E) {
  36.                 System.out.print("Ошибка, повторите ввод: ");
  37.             }
  38.         } while (isCorrect);
  39.         return num;
  40.     }
  41.  
  42.     static int enterIndex(int size) {
  43.         int index;
  44.         boolean isInCorrect;
  45.         do {
  46.             isInCorrect = false;
  47.             index = enterValue();
  48.             if (index < MIN_INDEX || index > size) {
  49.                 System.out.println("Данное значение должно быть больше нуля и меньше длины списка. Повторите ввод: ");
  50.                 isInCorrect = true;
  51.             }
  52.         } while (isInCorrect);
  53.         return index;
  54.     }
  55.  
  56.     static int enterColCount() {
  57.         int index;
  58.         boolean isCorrect;
  59.         do {
  60.             isCorrect = false;
  61.             index = enterValue();
  62.             if (index < 1 || index > 6) {
  63.                 System.out.println("Количество курсов колледжа не может быть меньше 1 или больше 6 ");
  64.                 isCorrect = true;
  65.             }
  66.         } while (isCorrect);
  67.         return index;
  68.     }
  69.  
  70.     static boolean isCorrectChoice(int choice) {
  71.         boolean isInCorrect;
  72.         isInCorrect = choice != CREATE_LIST && choice != OPEN_LIST;
  73.         return isInCorrect;
  74.     }
  75.  
  76.     static void printSelection(boolean isInCorrect, int choice) {
  77.         if (!isInCorrect) {
  78.             System.out.println("Вы выбрали вариант " + choice);
  79.             System.out.println("---------------------------------------------");
  80.         } else {
  81.             System.out.print("Пожалуйста, выберите указанные варианты: ");
  82.         }
  83.     }
  84.  
  85.     static int getTheChoice() {
  86.         int choice;
  87.         boolean isInCorrect;
  88.         do {
  89.             choice = enterValue();
  90.             isInCorrect = isCorrectChoice(choice);
  91.             printSelection(isInCorrect, choice);
  92.         } while (isInCorrect);
  93.         return choice;
  94.     }
  95.  
  96.     static void printMainMenu() {
  97.         System.out.println("\nПрограмма работы с списком студентов");
  98.         System.out.println("---------------------------------------");
  99.         System.out.print("Создать новый список(1) \nОткрыть список из файла(2)\n\nВвод: ");
  100.     }
  101.  
  102.     static boolean IsFileExist(String path) {
  103.         boolean isCorrect;
  104.         File inputFile = new File(path);
  105.         if (inputFile.exists()) {
  106.             isCorrect = true;
  107.         } else {
  108.             isCorrect = false;
  109.             System.out.print("Указанного файла не существует. Повторите ввод: ");
  110.         }
  111.         return isCorrect;
  112.     }
  113.  
  114.     static boolean isCorrectSizeFile(String path) {
  115.         boolean isCorrect = true;
  116.         File inputFile = new File(path);
  117.         if (inputFile.length() == 0) {
  118.             System.out.print("Файл пустой, повторите ввод: ");
  119.             isCorrect = false;
  120.         }
  121.         return isCorrect;
  122.     }
  123.  
  124.     static boolean isFileCorrect(String path) throws IOException {
  125.         Scanner scannerFile = new Scanner(new File(path));
  126.         boolean isCorrect = true;
  127.         while (scannerFile.hasNextLine() && isCorrect) {
  128.             try {
  129.                 scannerFile.nextLine();
  130.             } catch (Exception E) {
  131.                 System.out.println("Данные в указанном файле не соответсвуют условию");
  132.                 isCorrect = false;
  133.             }
  134.         }
  135.         scannerFile.close();
  136.         return isCorrect;
  137.     }
  138.  
  139.     static String enterPath() throws IOException {
  140.         String path;
  141.         boolean isCorrect;
  142.         System.out.print("Введите адрес файла: ");
  143.         do {
  144.             path = scannerConsole.nextLine();
  145.             isCorrect = (IsFileExist(path) && isCorrectSizeFile(path) && isFileCorrect(path));
  146.         } while (!isCorrect);
  147.         return path;
  148.     }
  149.  
  150.     private static boolean checkData(String name, String group) {
  151.         boolean isCorrect = true;
  152.         try {
  153.             if (name.equals("")) {
  154.                 isCorrect = false;
  155.             }
  156.             String namePattern = "^[а-яА-Я]+ [А-Я]\\.[А-Я]\\.$";
  157.             if (isCorrect && name.length() > 20) {
  158.                 isCorrect = false;
  159.             }
  160.  
  161.             if (isCorrect && !name.matches(namePattern)) {
  162.                 isCorrect = false;
  163.             }
  164.  
  165.             String groupPattern = "^\\d{6}$";
  166.             if (group.equals("")) {
  167.                 isCorrect = false;
  168.             }
  169.  
  170.             if (isCorrect && !group.matches(groupPattern)) {
  171.                 isCorrect = false;
  172.             }
  173.  
  174.         } catch (Exception var9) {
  175.             isCorrect = false;
  176.         }
  177.  
  178.         return isCorrect;
  179.     }
  180.  
  181.     static void fillListFromFile(String path) throws IOException, ClassNotFoundException {
  182.         File fileOfRecords = new File(path);
  183.         try {
  184.             BufferedReader reader = new BufferedReader(new FileReader(fileOfRecords));
  185.             try {
  186.                 String buff;
  187.                 if (fileOfRecords.length() != 0L && !(buff = reader.readLine()).equals("")) {
  188.                     int amount = Integer.parseInt(buff);
  189.                     int i = 0;
  190.                     boolean isCorrectData = true;
  191.                     while (isCorrectData && i < amount) {
  192.                         String name = reader.readLine();
  193.                         String group = reader.readLine();
  194.                         String course = reader.readLine();
  195.                         isCorrectData = checkData(name, group);
  196.                         if (isCorrectData) {
  197.                             Student comp = new Student(name, group, course);
  198.                             listInt.insertLast(comp);
  199.                             ++i;
  200.                         } else {
  201.                             System.err.println("Данные в файле некорректны.\n");
  202.                             selectionMenu();
  203.                         }
  204.                     }
  205.                 }
  206.             } catch (Throwable var15) {
  207.                 try {
  208.                     reader.close();
  209.                 } catch (Throwable var14) {
  210.                     var15.addSuppressed(var14);
  211.                 }
  212.             }
  213.             reader.close();
  214.         } catch (FileNotFoundException var16) {
  215.             System.out.println("Файл не найден.\n");
  216.             selectionMenu();
  217.         } catch (IOException var17) {
  218.             System.out.println("Доступ к файлу закрыт.\n");
  219.             selectionMenu();
  220.         }
  221.     }
  222.  
  223.     static void openListFromFile() throws IOException, ClassNotFoundException {
  224.         listInt.clear();
  225.         System.out.println("Открытие списка");
  226.         System.out.println("---------------------------------------------");
  227.         String path = enterPath();
  228.         fillListFromFile(path);
  229.     }
  230.  
  231.     static void openList(int choice) throws IOException, ClassNotFoundException {
  232.         if (choice == OPEN_LIST) {
  233.             openListFromFile();
  234.         }
  235.     }
  236.  
  237.     static boolean isCorrectChoiceForMenu(int choice) {
  238.         boolean isCorrect;
  239.         isCorrect = choice != ADD_ELEMENT && choice != DELETE_ELEMENT && choice != VIEW_LIST
  240.                 && choice != SAVE_LIST_OF_MENU && choice != OPEN_LIST_OF_MENU && choice != MAIN_TASK
  241.                 && choice != EXIT_PROGRAM;
  242.         return isCorrect;
  243.     }
  244.  
  245.     static int inputTheChoiceForMenu() {
  246.         int choice;
  247.         boolean isCorrect;
  248.         do {
  249.             choice = enterValue();
  250.             isCorrect = isCorrectChoiceForMenu(choice);
  251.             printSelection(isCorrect, choice);
  252.         } while (isCorrect);
  253.         return choice;
  254.     }
  255.  
  256.     static void printInfoMenu() {
  257.         System.out.println("---------------------------------------------");
  258.         System.out.println("\t\t\tОдносвязный список студентов");
  259.         System.out.println("---------------------------------------------");
  260.         System.out.println("Выберите действие, которое вы хотите выполнить:");
  261.         System.out.println("(1)Добавление студента в список");
  262.         System.out.println("(2)Удаление студента");
  263.         System.out.println("(3)Просмотр студентов");
  264.         System.out.println("(4)Удаление студентов последнего курса и увеличение курсов оставшихся студентов на год");
  265.         System.out.println("(5)Сохранение списка");
  266.         System.out.println("(6)Открыть список");
  267.         System.out.println("(0)Выход");
  268.         System.out.print("Ввод: ");
  269.     }
  270.  
  271.     static void addElements() {
  272.         Student Student = new Student();
  273.         Student.create(date, coursesCol);
  274.         listInt.insertLast(Student);
  275.     }
  276.  
  277.     static void addElementsMenu() throws IOException, ClassNotFoundException {
  278.         System.out.println("Добавление студента в список");
  279.         System.out.println("----------------------------------");
  280.         addElements();
  281.         selectionMenu();
  282.     }
  283.  
  284.     static void viewList() {
  285.         if (listInt.getSize() > 0) {
  286.             listInt.outputList();
  287.         } else {
  288.             System.out.println("Список пуст");
  289.         }
  290.     }
  291.  
  292.     static void delStudentByIndex() {
  293.         System.out.print("Введите номер студента, который хотите удалить: ");
  294.         int num = enterIndex(listInt.getSize());
  295.         listInt.deleteByIndex(num);
  296.     }
  297.  
  298.     static void getCoursesCol(){
  299.         System.out.println("Введите количество курсов колледжа");
  300.         System.out.print("Ввод: ");
  301.         coursesCol = enterColCount();
  302.     }
  303.  
  304.     static void deleteElementMenu() {
  305.         if (listInt.getSize() > 0) {
  306.             delStudentByIndex();
  307.         } else {
  308.             System.out.println("Список пуст");
  309.         }
  310.     }
  311.  
  312.     private static int enterTheMonth() {
  313.         boolean isInCorrect;
  314.         int month;
  315.         do {
  316.             isInCorrect = false;
  317.             System.out.println("Введите месяц");
  318.             System.out.println("Пример: 06");
  319.             System.out.print("Ввод: ");
  320.             month = enterValue();
  321.             if ((month < 1) || (month > 12)) {
  322.                 System.err.println("\nВведите номер месяца (от 01 до 12)");
  323.                 isInCorrect = true;
  324.             }
  325.         }while (isInCorrect);
  326.         return month;
  327.     }
  328.  
  329.     private static int enterTheYear() {
  330.         boolean isInCorrect;
  331.         int year;
  332.         do {
  333.             isInCorrect = false;
  334.             System.out.println("Введите год");
  335.             System.out.println("Пример: 2020");
  336.             System.out.print("Ввод: ");
  337.             year = enterValue();
  338.             if (String.valueOf(year).length() != 4) {
  339.                 System.err.println("\nПовторите ввод. Дата введена некорректно");
  340.                 isInCorrect = true;
  341.             }
  342.             if ((year < 2000) | (year > 2030)) {
  343.                 System.err.println("\nВведите год (в диапозоне от 2000 до 2030)");
  344.                 isInCorrect = true;
  345.             }
  346.         }while (isInCorrect);
  347.         return year;
  348.     }
  349.  
  350.     private static void enterTheDate() {
  351.         int month = enterTheMonth();
  352.         int year = enterTheYear();
  353.         if (month > 8) {
  354.             year--;
  355.         }
  356.         date = year;
  357.     }
  358.  
  359.     static void saveList() throws IOException {
  360.         System.out.println("\t\t\tСохранение списка");
  361.         System.out.println("---------------------------------------------");
  362.         System.out.print("Введите адрес: ");
  363.         String path = scannerConsole.nextLine();
  364.         FileWriter writer = new FileWriter(path);
  365.         writer.append(String.valueOf(listInt.getSize())).append("\n");
  366.         for (int i = 0; i < listInt.getSize(); i++) {
  367.             writer.append(listInt.getLinkByIndex(i + 1).info.name()).append("\n");
  368.             writer.append(listInt.getLinkByIndex(i + 1).info.group()).append("\n");
  369.             writer.append(listInt.getLinkByIndex(i + 1).info.course()).append("\n");
  370.         }
  371.         writer.flush();
  372.         System.out.println("Данные записаны в файл с адресом: " + path);
  373.     }
  374.  
  375.     static void checkSizeListForSave() throws IOException {
  376.         if (listInt.getSize() == 0) {
  377.             System.out.println("Список пуст");
  378.         } else {
  379.             saveList();
  380.         }
  381.     }
  382.  
  383.     static void mainTaskMenu() {
  384.         int choice = 0;
  385.         if (listInt.getSize() > 0) {
  386.             boolean isInCorrect;
  387.             do {
  388.                 isInCorrect = false;
  389.                 System.out.println("Вы уверены , что хотите удалить последний курс?");
  390.                 System.out.println("1 - Да, 2 - Нет");
  391.                 System.out.print("Ваш выбор: ");
  392.                 try {
  393.                     choice = Integer.parseInt(scannerConsole.nextLine());
  394.                 } catch (Exception E) {
  395.                     System.err.print("\nОшибка, повторите ввод: ");
  396.                     isInCorrect = true;
  397.                 }
  398.                 if (!((choice == 1) | (choice == 2))) {
  399.                     isInCorrect = true;
  400.                     System.err.println("\nНеверный выбор");
  401.                 }
  402.             } while (isInCorrect);
  403.             if (choice == 1) {
  404.                 listInt.deleteLastCourse(coursesCol);
  405.             }
  406.         } else {
  407.             System.out.println("\nСписок пуст");
  408.         }
  409.         System.out.println();
  410.     }
  411.  
  412.     static void selectionMenu() throws IOException, ClassNotFoundException {
  413.         printInfoMenu();
  414.         switch (inputTheChoiceForMenu()) {
  415.             case ADD_ELEMENT:
  416.                 addElementsMenu();
  417.                 selectionMenu();
  418.             case DELETE_ELEMENT:
  419.                 deleteElementMenu();
  420.                 selectionMenu();
  421.             case VIEW_LIST:
  422.                 viewList();
  423.                 selectionMenu();
  424.             case MAIN_TASK:
  425.                 mainTaskMenu();
  426.                 selectionMenu();
  427.             case SAVE_LIST_OF_MENU:
  428.                 checkSizeListForSave();
  429.                 selectionMenu();
  430.             case OPEN_LIST_OF_MENU:
  431.                 openListFromFile();
  432.                 selectionMenu();
  433.             case EXIT_PROGRAM:
  434.                 System.out.println("Конец программы");
  435.                 System.exit(0);
  436.         }
  437.     }
  438.  
  439.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  440.         scannerConsole = new Scanner(System.in);
  441.         listInt = new LinkList();
  442.         printMainMenu();
  443.         openList(getTheChoice());
  444.         enterTheDate();
  445.         getCoursesCol();
  446.         selectionMenu();
  447.         scannerConsole.close();
  448.     }
  449. }
  450.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement