Egor_Vakar

(Java) lab 5.1 Main

Mar 8th, 2022 (edited)
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.93 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3. import java.util.regex.PatternSyntaxException;
  4.  
  5. public class Main {
  6.     private static List list = null;
  7.     private static final Scanner sc = new Scanner(System.in);
  8.  
  9.     public static void main(String[] args) {
  10.         printHi();
  11.         showMenu();
  12.     }
  13.  
  14.     static void printHi() {
  15.         System.out.println("\n\n      Ку      \nЭта программа создана для работы с двусвязными списками\n");
  16.     }
  17.  
  18.     static void showMenu() {
  19.         int input;
  20.         do {
  21.             System.out.print("|||МЕНЮ|||\n1. Создать новый список.\n2. Добавить элемент.\n3. Удалить элемент.\n4. Показать список.\n5. Перевернуть список.\n6. Считать список из файла.\n7. Сохранить список в файл.\n0. Выход из программы.\nВыберите пункт меню: ");
  22.             input = takeInt(7);
  23.             userChoice(input);
  24.         } while (input != 0);
  25.  
  26.     }
  27.  
  28.     static int takeInt(final int MAX) {
  29.         boolean isIncorrect;
  30.         int num = -1;
  31.         do {
  32.             isIncorrect = false;
  33.             try {
  34.                 num = Integer.parseInt(sc.nextLine());
  35.             } catch (NumberFormatException e) {
  36.                 isIncorrect = true;
  37.             }
  38.             if (!isIncorrect) {
  39.                 isIncorrect = num > MAX || num < 0;
  40.             }
  41.             System.out.print(isIncorrect ? "\nНеверно! Введите число в диапазоне от 0 до " + MAX + ": " : "");
  42.         } while (isIncorrect);
  43.         return num;
  44.     }
  45.  
  46.     static void userChoice(int input) {
  47.         switch (input) {
  48.             case 0:
  49.                 System.out.println("Работа программы завершена");
  50.                 break;
  51.             case 1:
  52.                 createList();
  53.                 System.out.println("\n|||СПИСОК СОЗДАН|||\n");
  54.                 break;
  55.             case 2:
  56.                 if (list == null) {
  57.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! ДОБАВЛЕНИЕ ЭЛЕМЕНТА НЕВОЗМОЖНО|||\n");
  58.                 } else {
  59.                     addElement();
  60.                 }
  61.                 break;
  62.             case 3:
  63.                 if (list == null) {
  64.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! УДАЛЕНИЕ ЭЛЕМЕНТА НЕВОЗМОЖНО|||\n");
  65.                 } else {
  66.                     if (list.isEmpty()) {
  67.                         System.out.println("\n|||СПИСОК ПУСТ! УДАЛЕНИЕ НЕВОЗМОЖНО|||\n");
  68.                     } else {
  69.                         deleteElement();
  70.                     }
  71.                 }
  72.                 break;
  73.             case 4:
  74.                 if (list == null) {
  75.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! ВЫВОД НА ЭКРАН НЕВОЗМОЖЕН|||\n");
  76.                 } else {
  77.                     if (list.isEmpty()) {
  78.                         System.out.println("\n|||СПИСОК ПУСТ! ВЫВОД НА ЭКРАН НЕВОЗМОЖЕН|||\n");
  79.                     } else {
  80.                         System.out.println(list.printList());
  81.                     }
  82.                 }
  83.                 break;
  84.             case 5:
  85.                 if (list == null) {
  86.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! ПЕРЕВОРОТ СПИСКА НЕВОЗМОЖЕН|||\n");
  87.                 } else {
  88.                     if (list.isEmpty()) {
  89.                         System.out.println("\n|||СПИСОК ПУСТ! ПЕРЕВОРОТ СПИСКА НЕВОЗМОЖЕН|||\n");
  90.                     } else {
  91.                         reverseList();
  92.                     }
  93.                 }
  94.                 break;
  95.             case 6:
  96.                 if (list == null) {
  97.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! ЧТЕНИЕ ИЗ ФАЙЛА НЕВОЗМОЖНО|||\n");
  98.                 } else {
  99.                     readListFromFile();
  100.                 }
  101.                 break;
  102.             case 7:
  103.                 if (list == null) {
  104.                     System.out.println("\n|||СПИСОК НЕ СОЗДАН! СОХРАНЕНИЕ В ФАЙЛ НЕВОЗМОЖНО|||\n");
  105.                 } else {
  106.                     if (list.isEmpty()) {
  107.                         System.out.println("\n|||СПИСОК ПУСТ! СОХРАНЕНИЕ В ФАЙЛ НЕВОЗМОЖНО|||\n");
  108.                     } else {
  109.                         saveListToFile();
  110.                     }
  111.                 }
  112.         }
  113.     }
  114.  
  115.     static void saveListToFile() {
  116.         String path = takeOutPath();
  117.         try {
  118.             BufferedWriter writer = new BufferedWriter(new FileWriter(path));
  119.             try {
  120.                 writer.write(list.printList());
  121.                 System.out.println("\n|||СПИСОК УСПЕШНО СОХРАНЁН В ФАЙЛ|||\n");
  122.             } catch (Throwable var5) {
  123.                 try {
  124.                     writer.close();
  125.                 } catch (Throwable var4) {
  126.                     var5.addSuppressed(var4);
  127.                 }
  128.                 throw var5;
  129.             }
  130.             writer.close();
  131.         } catch (IOException var6) {
  132.             System.out.println("\n|||ОШИБКА ДОСТУПА|||\n");
  133.         }
  134.     }
  135.  
  136.     private static void readListFromFile() {
  137.         String path = takeInPath();
  138.         int size = 0;
  139.         final int MIN_SIZE = 1;
  140.         int lineCounter = 0;
  141.         final int SIZE_LINE_NUMBER = 1;
  142.         final int LIST_LINE_NUMBER = 2;
  143.         String line;
  144.         String[] listString = null;
  145.         boolean isCorrect = true;
  146.         try {
  147.             BufferedReader reader = new BufferedReader(new FileReader(path));
  148.             while ((isCorrect) && ((line = reader.readLine()) != null)) {
  149.                 lineCounter++;
  150.                 if (lineCounter == SIZE_LINE_NUMBER) {
  151.                     try {
  152.                         size = Integer.parseInt(line);
  153.                     } catch (Exception e) {
  154.                         System.out.println("\n|||НЕКОРЕТНЫЕ ДАННЫЕ В ФАЙЛЕ! ОШИБКА В СТРОКЕ РАЗМЕРА|||\n");
  155.                         isCorrect = false;
  156.                     }
  157.                     if (isCorrect && (size < MIN_SIZE)) {
  158.                         System.out.println("\n|||НЕКОРЕТНЫЕ ДАННЫЕ В ФАЙЛЕ! НЕКОРЕКТНО УКАЗАН РАЗМЕР!|||\n");
  159.                         isCorrect = false;
  160.                     }
  161.                 }
  162.                 if (lineCounter == LIST_LINE_NUMBER) {
  163.                     try {
  164.                         listString = line.split(" ");
  165.                     } catch (PatternSyntaxException e) {
  166.                         System.out.println("\n|||НЕКОРЕТНЫЕ ДАННЫЕ В ФАЙЛЕ! ОШИБКА В СТРОКЕ СПИСКА!|||\n");
  167.                         isCorrect = false;
  168.                     }
  169.                 }
  170.             }
  171.             reader.close();
  172.         } catch (IOException e) {
  173.             System.out.println("\n|||ОШИБКА ВВОДА/ВЫВОДА!|||\n");
  174.             isCorrect = false;
  175.         }
  176.         if ((isCorrect) && (((listString != null ? listString.length : 0) != size) || (lineCounter > LIST_LINE_NUMBER))) {
  177.             System.out.println("\n|||НЕКОРЕТНЫЕ ДАННЫЕ В ФАЙЛЕ!|||\n");
  178.             isCorrect = false;
  179.         } else {
  180.             for (int i = 0; i < size; i++) {
  181.                 assert listString != null;
  182.                 list.addElem(listString[i]);
  183.             }
  184.         }
  185.         if (isCorrect) {
  186.             System.out.println("\n|||СПИСОК УСПЕШНО СЧИТАН|||\n");
  187.         }
  188.     }
  189.  
  190.     static void reverseList() {
  191.         System.out.println("\n|||СПИСОК УСПЕШНО ПЕРЕВЁРНУТ|||\n");
  192.         list.reverse();
  193.     }
  194.  
  195.     static void addElement() {
  196.         System.out.println("\n|||ДОБАВЛЕНИЕ ЭЛЕМЕНТА|||\n");
  197.         System.out.print("Введите элемент: ");
  198.         list.addElem(sc.nextLine());
  199.         System.out.println("\n|||ЭЛЕМЕНТ ДОБАВЛЕН|||\n");
  200.     }
  201.  
  202.     static void deleteElement() {
  203.         System.out.println("\n|||УДАЛЕНИЕ ЭЛЕМЕНТА|||\n");
  204.         System.out.print("Введите индекс элемента: ");
  205.         int index = takeInt(list.getLength() - 1);
  206.         list.deleteElem(index);
  207.     }
  208.  
  209.     private static void createList() {
  210.         list = new List();
  211.     }
  212.  
  213.     static String takeInPath() {
  214.         String path;
  215.         boolean isIncorrect;
  216.         System.out.print("Введите адрес файла: ");
  217.         do {
  218.             isIncorrect = false;
  219.             path = sc.nextLine();
  220.             File file = new File(path);
  221.             if (!file.exists()) {
  222.                 System.out.print("Файл не найден\nВведите адрес файла: ");
  223.                 isIncorrect = true;
  224.             }
  225.             if (!isIncorrect && (!path.endsWith(".txt"))) {
  226.                 System.out.print("Файл найден, но это не \".txt\" файл\nВведите адрес файла: ");
  227.                 isIncorrect = true;
  228.             }
  229.         } while (isIncorrect);
  230.         return path;
  231.     }
  232.  
  233.     static String takeOutPath() {
  234.         String path;
  235.         boolean isIncorrect;
  236.         System.out.print("Введите адрес файла: ");
  237.         do {
  238.             isIncorrect = false;
  239.             path = sc.nextLine();
  240.             if (!path.endsWith(".txt")) {
  241.                 System.out.print("Это должен быть \".txt\" файл\nВведите адрес файла: ");
  242.                 isIncorrect = true;
  243.             }
  244.         } while (isIncorrect);
  245.         return path;
  246.     }
  247. }
Add Comment
Please, Sign In to add comment