Advertisement
Egor_Vakar

(Java) lab 7.2 Main

May 28th, 2022
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.56 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.nio.file.Files;
  8. import java.nio.file.Path;
  9. import java.util.Scanner;
  10.  
  11. public class Main {
  12.  
  13.     private static final Scanner scan = new Scanner(System.in);
  14.  
  15.     public static void main(String[] args) {
  16.         welcome();
  17.         int source = takeInputSource();
  18.         int[][] matrix = takeMatrix(source);
  19.         Node[] arr = findArray(matrix);
  20.         source = takeOutputSource();
  21.         output(source, arr);
  22.     }
  23.  
  24.     public static void welcome() {
  25.         System.out.println();
  26.         System.out.println("ВAC ПРИВЕТСТВУЕТ ПРОГРАММА ПЕРЕВОДА МАТРИЦЫ СМЕЖНОСТИ В СПИСКИ ИНЦИНДЕНЦИЙ");
  27.     }
  28.  
  29.     public static int takeInputSource() {
  30.         int source = 0;
  31.         boolean isInCorrect;
  32.         do {
  33.             isInCorrect = false;
  34.             System.out.print("\nВыберите источник матрицы:\n1. Файл\n2. Консоль\nВаш выбор: ");
  35.             try {
  36.                 source = Integer.parseInt(scan.nextLine());
  37.             } catch (NumberFormatException e) {
  38.                 System.out.print("\nОшибка! Число введено некорректно.\n");
  39.                 isInCorrect = true;
  40.             }
  41.  
  42.             if (!isInCorrect && (source != 2 && source != 1)) {
  43.                 System.out.print("\nОшибка! Число введено некорректно.\n");
  44.                 isInCorrect = true;
  45.             }
  46.         } while(isInCorrect);
  47.         return source;
  48.     }
  49.  
  50.     public static int takeOutputSource() {
  51.         int source = 0;
  52.         boolean isInCorrect;
  53.         do {
  54.             isInCorrect = false;
  55.             System.out.print("\nВыберите способ вывода:\n1. Файл\n2. Консоль\nВаш выбор: ");
  56.             try {
  57.                 source = Integer.parseInt(scan.nextLine());
  58.             } catch (NumberFormatException e) {
  59.                 System.out.print("\nОшибка! Число введено некорректно.\n");
  60.                 isInCorrect = true;
  61.             }
  62.  
  63.             if (!isInCorrect && (source != 2 && source != 1)) {
  64.                 System.out.print("\nОшибка! Число введено некорректно.\n");
  65.                 isInCorrect = true;
  66.             }
  67.         } while(isInCorrect);
  68.         return source;
  69.     }
  70.  
  71.     private static String takeInPath() {
  72.         String path;
  73.         boolean isIncorrect;
  74.         System.out.print("\nВведите путь к файлу: ");
  75.         do {
  76.             isIncorrect = false;
  77.             path = scan.nextLine();
  78.             if (Files.notExists(Path.of(path))) {
  79.                 System.out.print("Файл не найден\nВведите путь к файлу: ");
  80.                 isIncorrect = true;
  81.             }
  82.             if (!isIncorrect && (!path.endsWith(".txt"))) {
  83.                 System.out.print("Файл найден, но он нетипа \".txt\"\nВведите путь к файлу: ");
  84.                 isIncorrect = true;
  85.             }
  86.         }while (isIncorrect);
  87.         return path;
  88.     }
  89.  
  90.     static String takeOutPath() {
  91.         String path;
  92.         boolean isIncorrect;
  93.         System.out.print("\nВведите путь к файлу: ");
  94.         do {
  95.             isIncorrect = false;
  96.             path = scan.nextLine();
  97.             if (!path.endsWith(".txt")) {
  98.                 System.out.print("Это должен быть \".txt\" файл\nВведите путь к файлу: ");
  99.                 isIncorrect = true;
  100.             }
  101.         } while (isIncorrect);
  102.         return path;
  103.     }
  104.  
  105.     private static int takeInt(final int MIN_VALUE, final int MAX_VALUE) {
  106.         int num = 0;
  107.         boolean isInCorrect;
  108.         do {
  109.             isInCorrect = false;
  110.  
  111.             try {
  112.                 num = Integer.parseInt(scan.nextLine());
  113.             } catch (NumberFormatException e) {
  114.                 System.out.print("Ошибка! Введите число повторно: ");
  115.                 isInCorrect = true;
  116.             }
  117.  
  118.             if (!isInCorrect && (num < MIN_VALUE || num > MAX_VALUE)) {
  119.                 System.out.print("Ошибка! Введите число из диапазона[" + MIN_VALUE + "," + MAX_VALUE + "]: ");
  120.                 isInCorrect = true;
  121.             }
  122.         } while(isInCorrect);
  123.  
  124.         return num;
  125.     }
  126.  
  127.     private static int[][] takeMatrix(int source) {
  128.         int[][] matrix;
  129.         if (source == 1) {
  130.             String path = takeInPath();
  131.             matrix = takeMatrixFromFile(path);
  132.             while (matrix == null) {
  133.                 path = takeInPath();
  134.                 matrix = takeMatrixFromFile(path);
  135.             }
  136.         }
  137.         else {
  138.             System.out.print("\nВведите количество вершин графа: ");
  139.             int size = takeInt(2,13);
  140.             matrix = takeMatrixFromConsole(size);
  141.         }
  142.         return matrix;
  143.     }
  144.  
  145.     private static int[][] takeMatrixFromFile(final String path) {
  146.         int[][] matrix = null;
  147.         int size = 0;
  148.         int lineCounter = 0;
  149.         boolean isCorrect = true;
  150.         try(BufferedReader reader = new BufferedReader(new FileReader(path))) {
  151.             size = Integer.parseInt(reader.readLine());
  152.             lineCounter++;
  153.             if ((size < 2) || (size > 13)) {
  154.                 isCorrect = false;
  155.                 System.out.println("Некорректные данные!!");
  156.             }
  157.             else {
  158.                 matrix = new int[size][size];
  159.                 while (isCorrect && lineCounter < size + 1) {
  160.                     try {
  161.                         String[] line =  reader.readLine().split(" ");
  162.                         for (int i = 0; i < line.length; i++) {
  163.                             matrix[lineCounter - 1][i] = Integer.parseInt(line[i]);
  164.                             if ((lineCounter - 1 > i) && (matrix[lineCounter - 1][i] != matrix[i][lineCounter - 1])) {
  165.                                 System.out.println("\nМатрица заполнена неверно!");
  166.                                 isCorrect = false;
  167.                             }
  168.                         }
  169.                         lineCounter++;
  170.                     }
  171.                     catch (Exception e) {
  172.                         System.out.println("\nНекорректные данные!!");
  173.                         isCorrect = false;
  174.                     }
  175.                     }
  176.                 }
  177.         }catch (Exception e) {
  178.             System.out.println("\nОшибка ввода/вывода!!");
  179.             isCorrect = false;
  180.         }
  181.         if (!isCorrect || (lineCounter != size + 1)) {
  182.             matrix = null;
  183.         }
  184.         return matrix;
  185.     }
  186.  
  187.     private static int[][] takeMatrixFromConsole(final int size) {
  188.         int[][] matrix = new int[size][size];
  189.         for (int i = 0; i < size; i++) {
  190.             for (int j = 0; j < size; j++) {
  191.                 matrix[i][j] = 0;
  192.             }
  193.         }
  194.         for (int i = 0; i < size; i++) {
  195.             int j = -1;
  196.             while (j != 0) {
  197.                 System.out.print("\nВведите номер вершины, с которой связана вершина " + (i + 1) + ". Если хотите прекратить, введите 0: ");
  198.                 j = takeInt(0, size);
  199.                 if (j != 0) {
  200.                     if ( matrix[i][j - 1] == 1) {
  201.                         System.out.println("Эта вершина уже записана");
  202.                         j = -1;
  203.                     }
  204.                     else {
  205.                         System.out.println("Связь вершин " + (i + 1) + " и " + j + " записана успешно");
  206.                         matrix[i][j-1] = 1;
  207.                         matrix[j-1][i] = 1;
  208.                     }
  209.                 }
  210.             }
  211.         }
  212.         return matrix;
  213.     }
  214.  
  215.     private static Node[] findArray(int[][] matrix) {
  216.         Node[] arr = new Node[matrix.length];
  217.         for (int i = 0; i < matrix.length; i++) {
  218.             for (int j = 0; j < matrix.length; j++) {
  219.                 if (matrix[i][j] == 1) {
  220.                     Node newNode = new Node();
  221.                     newNode.setValue(j + 1);
  222.                     if (arr[i] == null) {
  223.                         arr[i] = newNode;
  224.                     }
  225.                     else {
  226.                         Node currentNode = arr[i];
  227.                         while (currentNode.getpNext() != null) {
  228.                             currentNode = currentNode.getpNext();
  229.                         }
  230.                         currentNode.setpNext(newNode);
  231.                     }
  232.                 }
  233.             }
  234.         }
  235.         return arr;
  236.     }
  237.  
  238.     private static void output(int source, Node[] arr) {
  239.         if (source == 1) {
  240.             String path = takeOutPath();
  241.             outputToFile(path, arr);
  242.         }
  243.         else {
  244.             outputToConsole(arr);
  245.         }
  246.     }
  247.  
  248.     private static void outputToConsole(Node[] arr) {
  249.         System.out.println("Списки инцинденций:");
  250.         for (int i = 0; i < arr.length; i++) {
  251.             System.out.print(i + 1 + ": ");
  252.             Node currentNode = arr[i];
  253.             while (currentNode.getpNext() != null) {
  254.                 System.out.print(currentNode.getValue() + " -> ");
  255.                 currentNode = currentNode.getpNext();
  256.             }
  257.             System.out.println(currentNode.getValue());
  258.         }
  259.     }
  260.  
  261.     static void outputToFile(final String path, final Node[] arr) {
  262.         try (FileWriter fw = new FileWriter(path)) {
  263.             fw.write("Списки инцинденций:\n");
  264.             for (int i = 0; i < arr.length; i++) {
  265.                 fw.write(i + 1 + ": ");
  266.                 Node currentNode = arr[i];
  267.                 while (currentNode.getpNext() != null) {
  268.                     fw.write(currentNode.getValue() + " -> ");
  269.                     currentNode = currentNode.getpNext();
  270.                 }
  271.                 fw.write(currentNode.getValue() + "\n");
  272.             }
  273.             System.out.println("Запись в файл прошла в штатном режиме :)");
  274.         } catch (Exception e) {
  275.             System.out.println("Ошибка при записи в файл!\nЗапись произведена в консоль:\n");
  276.             outputToConsole(arr);
  277.         }
  278.     }
  279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement