Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StudentList {
- private Student head;
- // Метод для добавления студента в список
- public void addStudent(Student newStudent) {
- newStudent.next = head;
- head = newStudent;
- }
- // Метод для добавления оценки студенту
- public void addMark(Student student, int subjectCode, int mark) {
- Marks newMark = new Marks(subjectCode, mark);
- newMark.next = student.marks;
- student.marks = newMark;
- }
- public void removeStudent(Student studentToRemove) {
- Student previousStudent = null;
- Student currentStudent = head;
- while (currentStudent != null && currentStudent != studentToRemove) {
- previousStudent = currentStudent;
- currentStudent = currentStudent.next;
- }
- if (currentStudent != null) {
- if (currentStudent.marks != null) {
- currentStudent.marks = null;
- }
- if (previousStudent != null) {
- previousStudent.next = currentStudent.next;
- } else {
- head = currentStudent.next;
- }
- }
- }
- public void printStudentsWithLowMarks() {
- Student currentStudent = head;
- if (currentStudent == null) {
- System.out.println("Список пуст! Добавьте запись");
- return;
- }
- boolean hasLowMarks = false;
- while (currentStudent != null) {
- Marks currentMark = currentStudent.marks;
- while (currentMark != null) {
- if (currentMark.mark < 4) {
- hasLowMarks = true;
- System.out.println("код группы: " + currentStudent.groupCode);
- System.out.println("фамилия: " + currentStudent.lastName);
- System.out.println("инициалы: " + currentStudent.initials);
- System.out.println("----------------------------");
- break;
- }
- currentMark = currentMark.next;
- }
- currentStudent = currentStudent.next;
- }
- if (!hasLowMarks) {
- System.out.println("Нет студентов с оценками ниже 4");
- }
- }
- public void printStudent() {
- Student currentStudent = head;
- if (currentStudent == null) {
- System.out.println("Список пуст!");
- return;
- }
- while (currentStudent != null) {
- String marks = "";
- Marks currentMarks = currentStudent.marks;
- while (currentMarks != null) {
- marks = marks + currentMarks.mark + " ";
- currentMarks = currentMarks.next;
- }
- System.out.print(currentStudent.groupCode + " ");
- System.out.print(currentStudent.lastName + " " + currentStudent.initials + " : ");
- System.out.println(marks);
- currentStudent = currentStudent.next;
- }
- }
- public int size() {
- int length = 0;
- Student currentStudent = head;
- while (currentStudent != null) {
- length++;
- currentStudent = currentStudent.next;
- }
- return length;
- }
- public Student getStudent(int num) {
- Student currentStudent = head;
- int i = 1;
- while (currentStudent != null && i != num) {
- i++;
- currentStudent = currentStudent.next;
- }
- return currentStudent;
- }
- public boolean checkRepeat(Student student) {
- Student currStudent = head;
- boolean isCorrect = true;
- while (currStudent != null) {
- if (currStudent == student) {
- isCorrect = false;
- System.out.println("Такая запись уже существует");
- break;
- }
- currStudent = currStudent.next;
- }
- return isCorrect;
- }
- public void replaceStudent(Student oldStudent, Student newStudent) { //int oldGroupCode, Student newStudent
- Student prevStudent = null;
- Student currentStudent = head;
- while (currentStudent != null && currentStudent != oldStudent) {
- prevStudent = currentStudent;
- currentStudent = currentStudent.next;
- }
- if (currentStudent != null) {
- if (prevStudent == null) {
- newStudent.next = head.next;
- head = newStudent;
- } else {
- newStudent.next = currentStudent.next;
- prevStudent.next = newStudent;
- }
- }
- }
- public Student getHead() {
- return head;
- }
- }
- public class Student {
- int groupCode;
- String lastName;
- String initials;
- Marks marks;
- Student next;
- Student(int groupCode, String lastName, String initials) {
- this.groupCode = groupCode;
- this.lastName = lastName;
- this.initials = initials;
- this.next = null;
- }
- }
- public class Marks {
- int subjectCode;
- int mark;
- Marks next;
- Marks(int subjectCode, int mark) {
- this.subjectCode = subjectCode;
- this.mark = mark;
- this.next = null;
- }
- }
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.*;
- public class Main {
- static Scanner scanner = new Scanner(System.in);
- static StudentList studentList = new StudentList();
- public static void main(String[] args) throws IOException {
- System.out.println("Эта программа выводит студентов, у которых есть оценки ниже 4\n");
- int num = 0;
- do {
- getInfo();
- num = getNum();
- getUserChoice(num);
- } while (num != 0);
- scanner.close();
- }
- private static void getInfo() {
- System.out.println("""
- 1 - Добавить студента в список\s
- 2 - Редактировать список\s
- 3 - Удалить студента из списка
- 4 - Показать весь список\s
- 5 - Сохранить список в файл\s
- 6 - Загрузить данные из файла
- 7 - Вывести информацию о студентах\s
- 0 - Нажмите чтобы выйти""");
- }
- private static int getNum() {
- int MIN = 0;
- int MAX = 7;
- int choose = 0;
- boolean isCorrect;
- do {
- isCorrect = true;
- try {
- choose = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных");
- }
- if (isCorrect & (choose < MIN || choose > MAX)) {
- isCorrect = false;
- }
- } while (!isCorrect);
- return choose;
- }
- private static void addRecord() {
- int code;
- String lastName;
- String initial;
- boolean isCorrect = true;
- code = addCode();
- lastName = addLastName();
- initial = addInitial();
- int size = addSize();
- int[] mark = new int[size];
- mark = addMark(size);
- Student student = new Student(code, lastName, initial);
- for (int i = size - 1; i >= 0; i--) {
- studentList.addMark(student, code, mark[i]);
- }
- isCorrect = studentList.checkRepeat(student);
- if (isCorrect) {
- studentList.addStudent(student);
- }
- }
- private static int addCode() {
- int MIN = 251001;
- int MAX = 251005;
- int code = 0;
- boolean isCorrect;
- do{
- isCorrect = true;
- System.out.print("Введите код группы " + MIN + " - " + MAX + ": ");
- try {
- code = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных");
- }
- if (isCorrect) {
- isCorrect = checkGroup(code);
- }
- } while (!isCorrect);
- return code;
- }
- private static boolean checkGroup(int num) {
- boolean isCorrect = false;
- int MIN = 251001;
- int MAX = 251005;
- if (num < MIN || num > MAX) {
- System.out.println("Ошибка номера введенной группы");
- } else {
- isCorrect = true;
- }
- return isCorrect;
- }
- private static String addLastName() {
- String name = "";
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.print("Введите фамилию студента: ");
- name = scanner.nextLine();
- isCorrect = checkName(name);
- } while (!isCorrect);
- return name;
- }
- private static boolean checkName(String name) {
- boolean isCorrect = false;
- int MIN = 2;
- int MAX = 15;
- if (name.length() < MIN || name.length() > MAX) {
- System.out.println("Вы вышли за пределы диапазона [2; 15]");
- } else {
- isCorrect = true;
- }
- return isCorrect;
- }
- private static String addInitial() {
- String init = "";
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.print("Введите инициалы студента: ");
- init = scanner.nextLine();
- isCorrect = checkInitial(init);
- } while (!isCorrect);
- return init;
- }
- private static boolean checkInitial(String initial) {
- boolean isCorrect = false;
- int MIN = 1;
- int MAX = 4;
- if (initial.length() < MIN || initial.length() > MAX) {
- System.out.println("Вы вышли за пределы диапазона [1; 4]");
- } else {
- isCorrect = true;
- }
- return isCorrect;
- }
- private static int[] addMark(int size) {
- boolean isCorrect;
- int[] mark = new int[size];
- for (int i = 0; i < size; i++) {
- do {
- isCorrect = true;
- System.out.println("Введите " + (i + 1) + " оценку");
- try {
- mark[i] = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность данных");
- }
- if (isCorrect) {
- isCorrect = checkMark(mark[i]);
- }
- } while (!isCorrect);
- }
- return mark;
- }
- public static boolean checkMark (int num) {
- boolean isCorrect = false;
- int MIN = 1;
- int MAX = 10;
- if (num < MIN || num > MAX) {
- System.out.println("Введите оценки от " + MIN + " до " + MAX);
- } else {
- isCorrect = true;
- }
- return isCorrect;
- }
- private static int addSize() {
- int num = 0;
- int MIN = 1;
- int MAX = 10;
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.println("Введите количество оценок у студента: ");
- try {
- num = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("");
- }
- if (isCorrect & (num < MIN || num > MAX)) {
- isCorrect = false;
- System.out.println("");
- }
- } while (!isCorrect);
- return num;
- }
- private static void deleteRecord() {
- if (studentList.size() == 0) {
- System.out.println("Список пуст! Добавьте запись");
- return;
- }
- Student student = getStudentOfRecord( "удалить");
- studentList.removeStudent(student);
- }
- private static Student getStudentOfRecord(String str) {
- int num = 0;
- final int MIN_NUM = 1;
- int length = studentList.size();
- boolean isIncorrect;
- do {
- isIncorrect = false;
- System.out.print("Введите номер записи которую хотите " + str + ": ");
- try {
- num = Integer.parseInt(scanner.nextLine());
- } catch (Exception q) {
- isIncorrect = true;
- System.out.println("Ошибка. Для ввода используйте цифры.");
- }
- if (!isIncorrect & (num < MIN_NUM || num > length)) {
- isIncorrect = true;
- System.out.println("Недопустимый диапазон входных данных.");
- }
- } while (isIncorrect);
- return studentList.getStudent(num);
- }
- private static void editRecord() {
- if (studentList.size() == 0) {
- System.out.println("Список пуст! Добавьте запись");
- return;
- }
- boolean isCorrect = true;
- Student student = getStudentOfRecord( "редактировать");
- int code = addCode();
- String lastName = addLastName();
- String initial = addInitial();
- int size = addSize();
- int[] mark = new int[size];
- mark = addMark(size);
- Student newStudent = new Student(code, lastName, initial);
- for (int i = size - 1; i >= 0; i--) {
- studentList.addMark(newStudent, code, mark[i]);
- }
- if (studentList.size() > 1) {
- isCorrect = studentList.checkRepeat(newStudent);
- }
- if (isCorrect) {
- studentList.replaceStudent(student, newStudent);
- }
- }
- private static String inputPath() {
- String path;
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.println("Введите полный путь к файлу");
- path = scanner.nextLine();
- File file = new File(path);
- if (!file.exists()) {
- isCorrect = false;
- System.out.println("Неверно введен путь");
- }
- if (!isCorrect && !file.canRead()) {
- System.out.println("Невозможно считать данные с файла");
- }
- if (!isCorrect && !file.canWrite()) {
- System.out.println("Невозможно записать данные в файл");
- }
- } while (!isCorrect);
- return path;
- }
- private static boolean checkDataCorrectness(String path) {
- boolean isCorrect = true;
- boolean isCorrectGroup, isCorrectName, isCorrectInitial, isCorrectMarks;
- String str;
- String[] mas;
- try {
- Scanner fileReader = new Scanner(new File(path));
- while((fileReader.hasNext()) & isCorrect) {
- str = fileReader.nextLine();
- mas = str.split(" ");
- if (mas.length < 4) {
- System.out.println("Недостаточно данных в файле");
- isCorrect = false;
- } else {
- isCorrectGroup = checkGroup(Integer.parseInt(mas[0]));
- isCorrectName = checkName(mas[1]);
- isCorrectInitial = checkInitial(mas[2]);
- isCorrectMarks = true;
- int i = 3;
- while (i < mas.length) {
- isCorrectMarks = checkMark(Integer.parseInt(mas[i]));
- i++;
- if (!isCorrectMarks) {
- break;
- }
- }
- if (!isCorrectGroup || !isCorrectName || !isCorrectInitial || !isCorrectMarks) {
- isCorrect = false;
- }
- }
- }
- } catch (Exception q) {
- System.out.println("Проверьте корректность данных в файле.");
- isCorrect = false;
- }
- return isCorrect;
- }
- private static void openData() throws FileNotFoundException {
- String path = inputPath();
- boolean IsCorrect = checkDataCorrectness(path);
- if (IsCorrect) {
- System.out.println("Данные были успешно считаны.");
- } else {
- return;
- }
- String str;
- boolean isIncorrect = true;
- String[] mas;
- Scanner fileReader = new Scanner(new File(path));
- while((fileReader.hasNext()) & isIncorrect) {
- str = fileReader.nextLine();
- mas = str.split(" ");
- Student student = new Student(Integer.parseInt(mas[0]), mas[1], mas[2]);
- int i = 3;
- while (i < mas.length) {
- studentList.addMark(student, Integer.parseInt(mas[0]), Integer.parseInt(mas[i]));
- i++;
- }
- isIncorrect = studentList.checkRepeat(student);
- if(isIncorrect) {
- studentList.addStudent(student);
- } else {
- System.out.println("Такая запись уже существует.");
- }
- }
- }
- private static void saveData(String path) throws IOException {
- if (studentList.size() == 0) {
- System.out.println("Список пуст!");
- return;
- }
- FileWriter writer = new FileWriter(path);
- Student currStudent = studentList.getHead();
- while (currStudent != null) {
- writer.write(currStudent.groupCode + " " + currStudent.lastName + " " + currStudent.initials + " ");
- Marks marks = currStudent.marks;
- while (marks != null) {
- writer.write(marks.mark + " ");
- marks = marks.next;
- }
- writer.write("\n");
- currStudent = currStudent.next;
- }
- writer.close();
- }
- private static void getUserChoice(int num) throws IOException {
- switch (num) {
- case 1 -> addRecord();
- case 2 -> editRecord();
- case 3 -> deleteRecord();
- case 4 -> studentList.printStudent();
- case 5 -> saveData(inputPath());
- case 6 -> openData();
- case 7 -> studentList.printStudentsWithLowMarks();
- case 0 -> System.exit(0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement