Advertisement
SmnVadik

Lab5.1 (Java)

Aug 19th, 2023
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.19 KB | None | 0 0
  1. public class StudentList {
  2.     private Student head;
  3.  
  4.     // Метод для добавления студента в список
  5.     public void addStudent(Student newStudent) {
  6.         newStudent.next = head;
  7.         head = newStudent;
  8.     }
  9.  
  10.     // Метод для добавления оценки студенту
  11.     public void addMark(Student student, int subjectCode, int mark) {
  12.         Marks newMark = new Marks(subjectCode, mark);
  13.         newMark.next = student.marks;
  14.         student.marks = newMark;
  15.     }
  16.  
  17.     public void removeStudent(Student studentToRemove) {
  18.         Student previousStudent = null;
  19.         Student currentStudent = head;
  20.         while (currentStudent != null && currentStudent != studentToRemove) {
  21.             previousStudent = currentStudent;
  22.             currentStudent = currentStudent.next;
  23.         }
  24.  
  25.         if (currentStudent != null) {
  26.             if (currentStudent.marks != null) {
  27.                 currentStudent.marks = null;
  28.             }
  29.  
  30.             if (previousStudent != null) {
  31.                 previousStudent.next = currentStudent.next;
  32.             } else {
  33.                 head = currentStudent.next;
  34.             }
  35.         }
  36.     }
  37.  
  38.     public void printStudentsWithLowMarks() {
  39.         Student currentStudent = head;
  40.         if (currentStudent == null) {
  41.             System.out.println("Список пуст! Добавьте запись");
  42.             return;
  43.         }
  44.         boolean hasLowMarks = false;
  45.         while (currentStudent != null) {
  46.             Marks currentMark = currentStudent.marks;
  47.             while (currentMark != null) {
  48.                 if (currentMark.mark < 4) {
  49.                     hasLowMarks = true;
  50.                     System.out.println("код группы: " + currentStudent.groupCode);
  51.                     System.out.println("фамилия: " + currentStudent.lastName);
  52.                     System.out.println("инициалы: " + currentStudent.initials);
  53.                     System.out.println("----------------------------");
  54.                     break;
  55.                 }
  56.                 currentMark = currentMark.next;
  57.             }
  58.             currentStudent = currentStudent.next;
  59.         }
  60.         if (!hasLowMarks) {
  61.             System.out.println("Нет студентов с оценками ниже 4");
  62.         }
  63.     }
  64.  
  65.     public void printStudent() {
  66.         Student currentStudent = head;
  67.         if (currentStudent == null) {
  68.             System.out.println("Список пуст!");
  69.             return;
  70.         }
  71.         while (currentStudent != null) {
  72.             String marks = "";
  73.             Marks currentMarks = currentStudent.marks;
  74.             while (currentMarks != null) {
  75.                 marks = marks + currentMarks.mark + " ";
  76.                 currentMarks = currentMarks.next;
  77.             }
  78.             System.out.print(currentStudent.groupCode + " ");
  79.             System.out.print(currentStudent.lastName + " " + currentStudent.initials + " : ");
  80.             System.out.println(marks);
  81.             currentStudent = currentStudent.next;
  82.         }
  83.     }
  84.  
  85.     public int size() {
  86.         int length = 0;
  87.         Student currentStudent = head;
  88.         while (currentStudent != null) {
  89.             length++;
  90.             currentStudent = currentStudent.next;
  91.         }
  92.         return length;
  93.     }
  94.  
  95.     public Student getStudent(int num) {
  96.         Student currentStudent = head;
  97.         int i = 1;
  98.         while (currentStudent != null && i != num) {
  99.             i++;
  100.             currentStudent = currentStudent.next;
  101.         }
  102.         return currentStudent;
  103.     }
  104.  
  105.     public boolean checkRepeat(Student student) {
  106.         Student currStudent = head;
  107.         boolean isCorrect = true;
  108.         while (currStudent != null) {
  109.             if (currStudent == student) {
  110.                 isCorrect = false;
  111.                 System.out.println("Такая запись уже существует");
  112.                 break;
  113.             }
  114.             currStudent = currStudent.next;
  115.         }
  116.         return isCorrect;
  117.     }
  118.  
  119.     public void replaceStudent(Student oldStudent, Student newStudent) { //int oldGroupCode, Student newStudent
  120.         Student prevStudent = null;
  121.         Student currentStudent = head;
  122.  
  123.         while (currentStudent != null && currentStudent != oldStudent) {
  124.             prevStudent = currentStudent;
  125.             currentStudent = currentStudent.next;
  126.         }
  127.  
  128.         if (currentStudent != null) {
  129.             if (prevStudent == null) {
  130.                 newStudent.next = head.next;
  131.                 head = newStudent;
  132.             } else {
  133.                 newStudent.next = currentStudent.next;
  134.                 prevStudent.next = newStudent;
  135.             }
  136.         }
  137.     }
  138.  
  139.     public Student getHead() {
  140.         return head;
  141.     }
  142.  
  143. }
  144.  
  145.  
  146. public class Student {
  147.     int groupCode;
  148.     String lastName;
  149.     String initials;
  150.     Marks marks;
  151.     Student next;
  152.  
  153.     Student(int groupCode, String lastName, String initials) {
  154.         this.groupCode = groupCode;
  155.         this.lastName = lastName;
  156.         this.initials = initials;
  157.         this.next = null;
  158.     }
  159.  
  160. }
  161.  
  162. public class Marks {
  163.     int subjectCode;
  164.     int mark;
  165.     Marks next;
  166.  
  167.     Marks(int subjectCode, int mark) {
  168.         this.subjectCode = subjectCode;
  169.         this.mark = mark;
  170.         this.next = null;
  171.     }
  172. }
  173.  
  174.  
  175. import java.io.File;
  176. import java.io.FileNotFoundException;
  177. import java.io.FileWriter;
  178. import java.io.IOException;
  179. import java.util.*;
  180.  
  181. public class Main {
  182.     static Scanner scanner = new Scanner(System.in);
  183.     static StudentList studentList = new StudentList();
  184.  
  185.     public static void main(String[] args) throws IOException {
  186.         System.out.println("Эта программа выводит студентов, у которых есть оценки ниже 4\n");
  187.         int num = 0;
  188.         do {
  189.             getInfo();
  190.             num = getNum();
  191.             getUserChoice(num);
  192.         } while (num != 0);
  193.         scanner.close();
  194.     }
  195.  
  196.     private static void getInfo() {
  197.         System.out.println("""
  198.                1 - Добавить студента в список\s
  199.                2 - Редактировать список\s
  200.                3 - Удалить студента из списка
  201.                4 - Показать весь список\s
  202.                5 - Сохранить список в файл\s
  203.                6 - Загрузить данные из файла
  204.                7 - Вывести информацию о студентах\s
  205.                0 - Нажмите чтобы выйти""");
  206.     }
  207.  
  208.     private static int getNum() {
  209.         int MIN = 0;
  210.         int MAX = 7;
  211.         int choose = 0;
  212.         boolean isCorrect;
  213.         do {
  214.             isCorrect = true;
  215.             try {
  216.                 choose = Integer.parseInt(scanner.nextLine());
  217.             } catch (Exception e) {
  218.                 isCorrect = false;
  219.                 System.out.println("Проверьте корректность данных");
  220.             }
  221.             if (isCorrect & (choose < MIN || choose > MAX)) {
  222.                 isCorrect = false;
  223.             }
  224.         } while (!isCorrect);
  225.         return choose;
  226.     }
  227.  
  228.  
  229.     private static void addRecord() {
  230.         int code;
  231.         String lastName;
  232.         String initial;
  233.         boolean isCorrect = true;
  234.         code = addCode();
  235.         lastName = addLastName();
  236.         initial = addInitial();
  237.         int size = addSize();
  238.  
  239.         int[] mark = new int[size];
  240.         mark = addMark(size);
  241.  
  242.         Student student = new Student(code, lastName, initial);
  243.         for (int i = size - 1; i >= 0; i--) {
  244.             studentList.addMark(student, code, mark[i]);
  245.         }
  246.  
  247.         isCorrect = studentList.checkRepeat(student);
  248.         if (isCorrect) {
  249.             studentList.addStudent(student);
  250.         }
  251.     }
  252.  
  253.     private static int addCode() {
  254.         int MIN = 251001;
  255.         int MAX = 251005;
  256.         int code = 0;
  257.         boolean isCorrect;
  258.         do{
  259.             isCorrect = true;
  260.             System.out.print("Введите код группы " + MIN + " - " + MAX + ": ");
  261.             try {
  262.                 code = Integer.parseInt(scanner.nextLine());
  263.             } catch (NumberFormatException e) {
  264.                 isCorrect = false;
  265.                 System.out.println("Проверьте корректность введенных данных");
  266.             }
  267.             if (isCorrect) {
  268.                 isCorrect = checkGroup(code);
  269.             }
  270.         } while (!isCorrect);
  271.         return code;
  272.     }
  273.  
  274.     private static boolean checkGroup(int num) {
  275.         boolean isCorrect = false;
  276.         int MIN = 251001;
  277.         int MAX = 251005;
  278.         if (num < MIN || num > MAX) {
  279.             System.out.println("Ошибка номера введенной группы");
  280.         } else {
  281.             isCorrect = true;
  282.         }
  283.         return isCorrect;
  284.     }
  285.  
  286.     private static String addLastName() {
  287.         String name = "";
  288.         boolean isCorrect;
  289.         do {
  290.             isCorrect = true;
  291.             System.out.print("Введите фамилию студента: ");
  292.             name = scanner.nextLine();
  293.             isCorrect = checkName(name);
  294.         } while (!isCorrect);
  295.         return name;
  296.     }
  297.  
  298.     private static boolean checkName(String name) {
  299.         boolean isCorrect = false;
  300.         int MIN = 2;
  301.         int MAX = 15;
  302.         if (name.length() < MIN || name.length() > MAX) {
  303.             System.out.println("Вы вышли за пределы диапазона [2; 15]");
  304.         } else {
  305.             isCorrect = true;
  306.         }
  307.         return isCorrect;
  308.     }
  309.  
  310.     private static String addInitial() {
  311.         String init = "";
  312.         boolean isCorrect;
  313.         do {
  314.             isCorrect = true;
  315.             System.out.print("Введите инициалы студента: ");
  316.             init = scanner.nextLine();
  317.             isCorrect = checkInitial(init);
  318.         } while (!isCorrect);
  319.         return init;
  320.     }
  321.  
  322.     private static boolean checkInitial(String initial) {
  323.         boolean isCorrect = false;
  324.         int MIN = 1;
  325.         int MAX = 4;
  326.         if (initial.length() < MIN || initial.length() > MAX) {
  327.             System.out.println("Вы вышли за пределы диапазона [1; 4]");
  328.         } else {
  329.             isCorrect = true;
  330.         }
  331.         return isCorrect;
  332.     }
  333.  
  334.     private static int[] addMark(int size) {
  335.         boolean isCorrect;
  336.         int[] mark = new int[size];
  337.         for (int i = 0; i < size; i++) {
  338.             do {
  339.                 isCorrect = true;
  340.                 System.out.println("Введите " + (i + 1) + " оценку");
  341.                 try {
  342.                     mark[i] = Integer.parseInt(scanner.nextLine());
  343.                 } catch (Exception e) {
  344.                     isCorrect = false;
  345.                     System.out.println("Проверьте корректность данных");
  346.                 }
  347.                 if (isCorrect) {
  348.                     isCorrect = checkMark(mark[i]);
  349.                 }
  350.             } while (!isCorrect);
  351.         }
  352.         return mark;
  353.     }
  354.  
  355.     public static boolean checkMark (int num) {
  356.         boolean isCorrect = false;
  357.         int MIN = 1;
  358.         int MAX = 10;
  359.         if (num < MIN || num > MAX) {
  360.             System.out.println("Введите оценки от " + MIN + " до " + MAX);
  361.         } else {
  362.             isCorrect = true;
  363.         }
  364.         return isCorrect;
  365.     }
  366.  
  367.     private static int addSize() {
  368.         int num = 0;
  369.         int MIN = 1;
  370.         int MAX = 10;
  371.         boolean isCorrect;
  372.         do {
  373.             isCorrect = true;
  374.             System.out.println("Введите количество оценок у студента: ");
  375.             try {
  376.                 num = Integer.parseInt(scanner.nextLine());
  377.             } catch (Exception e) {
  378.                 isCorrect = false;
  379.                 System.out.println("");
  380.             }
  381.             if (isCorrect & (num < MIN || num > MAX)) {
  382.                 isCorrect = false;
  383.                 System.out.println("");
  384.             }
  385.         } while (!isCorrect);
  386.         return num;
  387.     }
  388.  
  389.     private static void deleteRecord() {
  390.         if (studentList.size() == 0) {
  391.             System.out.println("Список пуст! Добавьте запись");
  392.             return;
  393.         }
  394.         Student student = getStudentOfRecord( "удалить");
  395.         studentList.removeStudent(student);
  396.     }
  397.  
  398.     private static Student getStudentOfRecord(String str) {
  399.         int num = 0;
  400.         final int MIN_NUM = 1;
  401.         int length = studentList.size();
  402.         boolean isIncorrect;
  403.         do {
  404.             isIncorrect = false;
  405.             System.out.print("Введите номер записи которую хотите " + str + ": ");
  406.             try {
  407.                 num = Integer.parseInt(scanner.nextLine());
  408.             } catch (Exception q) {
  409.                 isIncorrect = true;
  410.                 System.out.println("Ошибка. Для ввода используйте цифры.");
  411.             }
  412.             if (!isIncorrect & (num < MIN_NUM || num > length)) {
  413.                 isIncorrect = true;
  414.                 System.out.println("Недопустимый диапазон входных данных.");
  415.             }
  416.         } while (isIncorrect);
  417.         return studentList.getStudent(num);
  418.     }
  419.  
  420.     private static void editRecord() {
  421.         if (studentList.size() == 0) {
  422.             System.out.println("Список пуст! Добавьте запись");
  423.             return;
  424.         }
  425.         boolean isCorrect = true;
  426.         Student student = getStudentOfRecord( "редактировать");
  427.         int code = addCode();
  428.         String lastName = addLastName();
  429.         String initial = addInitial();
  430.         int size = addSize();
  431.         int[] mark = new int[size];
  432.         mark = addMark(size);
  433.  
  434.         Student newStudent = new Student(code, lastName, initial);
  435.         for (int i = size - 1; i >= 0; i--) {
  436.             studentList.addMark(newStudent, code, mark[i]);
  437.         }
  438.  
  439.         if (studentList.size() > 1) {
  440.             isCorrect = studentList.checkRepeat(newStudent);
  441.         }
  442.         if (isCorrect) {
  443.             studentList.replaceStudent(student, newStudent);
  444.         }
  445.     }
  446.  
  447.  
  448.     private static String inputPath() {
  449.         String path;
  450.         boolean isCorrect;
  451.         do {
  452.             isCorrect = true;
  453.             System.out.println("Введите полный путь к файлу");
  454.             path = scanner.nextLine();
  455.             File file = new File(path);
  456.             if (!file.exists()) {
  457.                 isCorrect = false;
  458.                 System.out.println("Неверно введен путь");
  459.             }
  460.             if (!isCorrect && !file.canRead()) {
  461.                 System.out.println("Невозможно считать данные с файла");
  462.             }
  463.             if (!isCorrect && !file.canWrite()) {
  464.                 System.out.println("Невозможно записать данные в файл");
  465.             }
  466.         } while (!isCorrect);
  467.         return path;
  468.     }
  469.  
  470.  
  471.     private static boolean checkDataCorrectness(String path) {
  472.         boolean isCorrect = true;
  473.         boolean isCorrectGroup, isCorrectName, isCorrectInitial, isCorrectMarks;
  474.         String str;
  475.         String[] mas;
  476.  
  477.         try {
  478.             Scanner fileReader = new Scanner(new File(path));
  479.             while((fileReader.hasNext()) & isCorrect) {
  480.                 str = fileReader.nextLine();
  481.                 mas = str.split(" ");
  482.                 if (mas.length < 4) {
  483.                     System.out.println("Недостаточно данных в файле");
  484.                     isCorrect = false;
  485.                 } else {
  486.                     isCorrectGroup = checkGroup(Integer.parseInt(mas[0]));
  487.                     isCorrectName = checkName(mas[1]);
  488.                     isCorrectInitial = checkInitial(mas[2]);
  489.                     isCorrectMarks = true;
  490.                     int i = 3;
  491.                     while (i < mas.length) {
  492.                         isCorrectMarks = checkMark(Integer.parseInt(mas[i]));
  493.                         i++;
  494.                         if (!isCorrectMarks) {
  495.                             break;
  496.                         }
  497.                     }
  498.  
  499.                     if (!isCorrectGroup || !isCorrectName || !isCorrectInitial || !isCorrectMarks) {
  500.                         isCorrect = false;
  501.                     }
  502.                 }
  503.             }
  504.         } catch (Exception q) {
  505.             System.out.println("Проверьте корректность данных в файле.");
  506.             isCorrect = false;
  507.         }
  508.         return isCorrect;
  509.     }
  510.  
  511.  
  512.  
  513.     private static void openData() throws FileNotFoundException {
  514.         String path = inputPath();
  515.         boolean IsCorrect = checkDataCorrectness(path);
  516.         if (IsCorrect) {
  517.             System.out.println("Данные были успешно считаны.");
  518.         } else {
  519.             return;
  520.         }
  521.         String str;
  522.         boolean isIncorrect = true;
  523.         String[] mas;
  524.         Scanner fileReader = new Scanner(new File(path));
  525.         while((fileReader.hasNext())  & isIncorrect) {
  526.             str = fileReader.nextLine();
  527.             mas = str.split(" ");
  528.             Student student = new Student(Integer.parseInt(mas[0]), mas[1],  mas[2]);
  529.             int i = 3;
  530.             while (i < mas.length) {
  531.                 studentList.addMark(student, Integer.parseInt(mas[0]), Integer.parseInt(mas[i]));
  532.                 i++;
  533.             }
  534.             isIncorrect = studentList.checkRepeat(student);
  535.  
  536.             if(isIncorrect) {
  537.                 studentList.addStudent(student);
  538.             } else {
  539.                 System.out.println("Такая запись уже существует.");
  540.             }
  541.         }
  542.     }
  543.  
  544.     private static void saveData(String path) throws IOException {
  545.         if (studentList.size() == 0) {
  546.             System.out.println("Список пуст!");
  547.             return;
  548.         }
  549.         FileWriter writer = new FileWriter(path);
  550.         Student currStudent = studentList.getHead();
  551.         while (currStudent != null) {
  552.             writer.write(currStudent.groupCode + " " + currStudent.lastName + " " + currStudent.initials + " ");
  553.             Marks marks = currStudent.marks;
  554.             while (marks != null) {
  555.                 writer.write(marks.mark + " ");
  556.                 marks = marks.next;
  557.             }
  558.             writer.write("\n");
  559.             currStudent = currStudent.next;
  560.         }
  561.         writer.close();
  562.     }
  563.  
  564.     private static void getUserChoice(int num) throws IOException {
  565.         switch (num) {
  566.             case 1 -> addRecord();
  567.             case 2 -> editRecord();
  568.             case 3 -> deleteRecord();
  569.             case 4 -> studentList.printStudent();
  570.             case 5 -> saveData(inputPath());
  571.             case 6 -> openData();
  572.             case 7 -> studentList.printStudentsWithLowMarks();
  573.             case 0 -> System.exit(0);
  574.         }
  575.     }
  576. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement