Advertisement
Egor_Vakar

(Java) lab 7.1 Main

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