Advertisement
SmnVadik

Lab 7.2 (Java)

Sep 13th, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.70 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3.  
  4. public class Main {
  5.     private static final int MIN_SIZE = 1;
  6.     private static final int MAX_SIZE = 9;
  7.     private static final int MIN_VALUE = 0;
  8.     private static final Scanner scan = new Scanner(System.in);
  9.  
  10.     public static void outputTaskInfo() {
  11.         System.out.println("Данная программа преобразует данные списки инцидентности в матрицу смежности." + "\n" +
  12.                 "Диапазон ввода значения количества вершин: " + MIN_SIZE + "..." + MAX_SIZE + ".");
  13.     }
  14.  
  15.     public static int getVerificationOfChoice() {
  16.         int choice = 0;
  17.         boolean isIncorrect;
  18.  
  19.         do {
  20.             isIncorrect = false;
  21.             try {
  22.                 choice = Integer.parseInt(scan.nextLine());
  23.             } catch (NumberFormatException e) {
  24.                 System.out.println("Проверьте корректность ввода данных!");
  25.                 isIncorrect = true;
  26.             }
  27.             if (!isIncorrect && (choice != 0 && choice != 1)) {
  28.                 System.out.println("Для выбора введите 0 или 1!");
  29.                 isIncorrect = true;
  30.             }
  31.         } while (isIncorrect);
  32.  
  33.         return choice;
  34.     }
  35.  
  36.     public static String inputPathToFile() {
  37.         boolean isIncorrect;
  38.         String path;
  39.  
  40.         System.out.println("Укажите путь к файлу: ");
  41.  
  42.         do {
  43.             isIncorrect = false;
  44.             path = scan.nextLine();
  45.             File file = new File(path);
  46.  
  47.             if (!file.exists()) {
  48.                 System.out.println("По указанному пути файл не найден! Укажите правильный путь: ");
  49.                 isIncorrect = true;
  50.             }
  51.         } while (isIncorrect);
  52.  
  53.         return path;
  54.     }
  55.  
  56.     public static int readSizeFromConsole(){
  57.         int size = 0;
  58.         boolean isIncorrect;
  59.  
  60.         System.out.println("Введите значение размера матрицы: ");
  61.  
  62.         do {
  63.             isIncorrect = false;
  64.             try {
  65.                 size = Integer.parseInt(scan.nextLine());
  66.             } catch (NumberFormatException e) {
  67.                 System.out.println("Проверьте корректность ввода данных!");
  68.                 isIncorrect = true;
  69.             }
  70.             if (!isIncorrect && (size < MIN_SIZE || size > MAX_SIZE)) {
  71.                 System.out.println("Введите число от " + MIN_SIZE + " до " + MAX_SIZE + "! \n");
  72.                 isIncorrect = true;
  73.             }
  74.         } while (isIncorrect);
  75.  
  76.         return size;
  77.     }
  78.  
  79.     public static int readSizeFromFile(final String path) {
  80.         int size;
  81.  
  82.         System.out.println("Происходит чтение количества вершин...");
  83.  
  84.         try (BufferedReader br = new BufferedReader(new FileReader(path))) {
  85.             size = Integer.parseInt(br.readLine());
  86.         } catch (Exception e) {
  87.             System.out.println("Ошибка при считывании количества вершин из файла!Введите количество с консоли!");
  88.             size = readSizeFromConsole();
  89.         }
  90.  
  91.         return size;
  92.     }
  93.  
  94.     public static void outputSize(final int choice, int size, String path) {
  95.         boolean isIncorrect;
  96.  
  97.         if (choice == 0)
  98.             System.out.println("Количество вершин равно " + size + ".");
  99.         if (choice == 1) {
  100.             System.out.println("Вывод значения количества вершин в файл...");
  101.  
  102.             do {
  103.                 isIncorrect = false;
  104.                 try {
  105.                     FileWriter writer = new FileWriter(path);
  106.                     writer.write("Кол-во вершин: " + size + "\n");
  107.                     writer.close();
  108.                 } catch (IOException e) {
  109.                     isIncorrect = true;
  110.                     System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!");
  111.                     path = inputPathToFile();
  112.                 }
  113.             } while (isIncorrect);
  114.  
  115.             System.out.println("Данные успешно записаны в файл!");
  116.         }
  117.     }
  118.  
  119.     public static int[][] fillMatrixFromConsole(final int size) {
  120.         int[][] matrix = new int[size][size];
  121.         boolean isIncorrect;
  122.  
  123.         for (int i = 0; i < size; i++) {
  124.             for (int j = 0; j < size; j++) {
  125.                 System.out.print("Введите " + (j + 1) + "-ое значение для " + (i + 1) + "-ой вершины: " );
  126.  
  127.                 do {
  128.                     isIncorrect = false;
  129.                     try {
  130.                         matrix[i][j] = Integer.parseInt(scan.nextLine());
  131.                     } catch (NumberFormatException e) {
  132.                         System.out.println("Проверьте корректность ввода данных!");
  133.                         isIncorrect = true;
  134.                     }
  135.  
  136.                     if (!isIncorrect && (matrix[i][j] < 0 || matrix[i][j] > size)) {
  137.                         isIncorrect = true;
  138.                         System.out.println("Введите значение от " + MIN_VALUE + " до " + size + "!");
  139.                     }
  140.                 } while (isIncorrect);
  141.             }
  142.         }
  143.  
  144.         return matrix;
  145.     }
  146.  
  147.     public static int[][] fillMatrixFromFile (final int size, final String path) throws FileNotFoundException {
  148.         int[][] matrix = new int[size][size];
  149.         int count = 0 ;
  150.         Scanner fr = new Scanner(new File(path));
  151.  
  152.         System.out.println("Чтение списков инцидентности ...");
  153.         fr.nextLine();
  154.         while (fr.hasNext()) {
  155.             fr.next();
  156.             count++;
  157.         }
  158.  
  159.         fr.close();
  160.  
  161.         if (count > size * size) {
  162.             System.out.println("Ошибка при чтении списков инцидентности! Введите списки с консоли!");
  163.             matrix = fillMatrixFromConsole(size);
  164.         } else {
  165.             fr = new Scanner(new File(path));
  166.             fr.nextLine();
  167.  
  168.             for (int i = 0; i < size; i++) {
  169.                 for (int j = 0; j < size; j++) {
  170.                     try {
  171.                         matrix[i][j] = fr.nextInt();
  172.                     } catch (Exception e) {
  173.                         System.out.println("Ошибка при считывании списков инцидентности из файла!Введите списки с консоли!");
  174.                         matrix = fillMatrixFromConsole(size);
  175.                     }
  176.                     if (matrix[i][j] < MIN_VALUE || matrix[i][j] > size) {
  177.                         System.out.println("Ошибка при считывании списков инцидентности из файла! Введите списки с консоли!");
  178.                         matrix = fillMatrixFromConsole(size);
  179.                     }
  180.                 }
  181.             }
  182.         }
  183.  
  184.         return matrix;
  185.     }
  186.  
  187.     public static void outputMatrix(final int choice, String path, final int[][] matrix, final int size) {
  188.         boolean isIncorrect;
  189.  
  190.         if (choice == 0) {
  191.             System.out.println("Вывод списков инцидентности: ");
  192.  
  193.             for (int i = 0; i < size; i++)
  194.             {
  195.                 int j = 0;
  196.                 System.out.print((i + 1) + "-ая вершина: ");
  197.                 while (j < size && matrix[i][j] > 0) {
  198.                     System.out.print(matrix[i][j] + " -> ");
  199.                     j++;
  200.                 }
  201.                 System.out.println("nil");
  202.             }
  203.         }
  204.  
  205.         if (choice == 1) {
  206.             System.out.println("Вывод списков инцидентности в файл...");
  207.  
  208.             do {
  209.                 isIncorrect = false;
  210.                 try {
  211.                     FileWriter writer = new FileWriter(path, true);
  212.                     BufferedWriter bufferWriter = new BufferedWriter(writer);
  213.  
  214.                     for (int i = 0; i < size; i++)
  215.                     {
  216.                         int j = 0;
  217.                         bufferWriter.write((i + 1) + "-ая вершина: ");
  218.                         while (j < size && matrix[i][j] > 0) {
  219.                             bufferWriter.write(matrix[i][j] + " -> ");
  220.                             j++;
  221.                         }
  222.                         bufferWriter.write("nil\n");
  223.                     }
  224.                     bufferWriter.close();
  225.                     writer.close();
  226.                 } catch (IOException e) {
  227.                     isIncorrect = true;
  228.                     System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!");
  229.                     path = inputPathToFile();
  230.                 }
  231.             } while (isIncorrect);
  232.  
  233.             System.out.println("Данные успешно записаны в файл!");
  234.         }
  235.     }
  236.  
  237.     public static int[][] ConvertMatrix(final int size, final int[][] matrix){
  238.         int[][] adjacencyMatrix = new int [size][size];
  239.  
  240.         for (int i = 0; i < size; i++) {
  241.             int j = 0;
  242.             while (j < size) {
  243.                 adjacencyMatrix[i][j] = 0;
  244.                 j++;
  245.             }
  246.             j = 0;
  247.             while (j < size && matrix[i][j] != 0) {
  248.                 adjacencyMatrix[i][matrix[i][j] - 1] = 1;
  249.                 j++;
  250.             }
  251.         }
  252.         return adjacencyMatrix;
  253.     }
  254.  
  255.     public static void outputAdjacencyMatrix(final int choice, String path, final int[][] matrix, final int size) {
  256.         boolean isIncorrect;
  257.  
  258.         if (choice == 0) {
  259.             System.out.println("Вывод матрицы смежности: ");
  260.             System.out.print("\t");
  261.             for (int i = 0; i < size; i++)
  262.             {
  263.                 System.out.print((i + 1) + "\t");
  264.             }
  265.  
  266.             System.out.print("\n");
  267.             for (int i = 0; i < size; i++)
  268.             {
  269.                 System.out.print((i + 1) + "\t");
  270.                 for (int j = 0; j < size; j++)
  271.                     System.out.print(matrix[i][j] + "\t");
  272.                 System.out.print("\n");
  273.             }
  274.             System.out.print("\n");
  275.         }
  276.  
  277.         if (choice == 1) {
  278.             System.out.println("Вывод матрицы смежности в файл...");
  279.  
  280.             do {
  281.                 isIncorrect = false;
  282.                 try {
  283.                     FileWriter writer = new FileWriter(path, true);
  284.                     BufferedWriter bufferWriter = new BufferedWriter(writer);
  285.  
  286.                     bufferWriter.write("\t");
  287.                     for (int i = 0; i < size; i++)
  288.                     {
  289.                         bufferWriter.write((i + 1) + "\t");
  290.                     }
  291.                     bufferWriter.write("\n");
  292.                     for (int i = 0; i < size; i++)
  293.                     {
  294.                         bufferWriter.write((i + 1) + "\t");
  295.                         for (int j = 0; j < size; j++)
  296.                             bufferWriter.write(matrix[i][j] + "\t");
  297.                         bufferWriter.write("\n");
  298.                     }
  299.                     bufferWriter.write("\n");
  300.  
  301.                     bufferWriter.close();
  302.                     writer.close();
  303.                 } catch (IOException e) {
  304.                     isIncorrect = true;
  305.                     System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!");
  306.                     path = inputPathToFile();
  307.                 }
  308.             } while (isIncorrect);
  309.  
  310.             System.out.println("Данные успешно записаны в файл!");
  311.         }
  312.     }
  313.  
  314.     public static int[][] processUserInput() throws FileNotFoundException {
  315.         int size = 0;
  316.         int choiceForInput;
  317.         int[][] matrix = new int[0][];
  318.         String pathToIn = "";
  319.  
  320.         System.out.println("Вы желаете ввести данные с консоли(0) или взять данные из файла(1)?");
  321.         choiceForInput = getVerificationOfChoice();
  322.  
  323.         if (choiceForInput == 0) {
  324.             size = readSizeFromConsole();
  325.             matrix = fillMatrixFromConsole(size);
  326.         }
  327.         if (choiceForInput == 1) {
  328.             pathToIn = inputPathToFile();
  329.             size = readSizeFromFile(pathToIn);
  330.             matrix = fillMatrixFromFile(size, pathToIn);
  331.         }
  332.  
  333.         return matrix;
  334.     }
  335.  
  336.     public static void processUserOutput(int size, int[][] matrix, int[][] adjacencyMatrix) {
  337.         int choiceForOutput;
  338.         String pathToOut = "";
  339.  
  340.         System.out.println("Вы желаете получить результат в консоли(0) или в файле(1)?");
  341.         choiceForOutput = getVerificationOfChoice();
  342.  
  343.         if (choiceForOutput == 1)
  344.             pathToOut = inputPathToFile();
  345.         outputSize(choiceForOutput, size, pathToOut);
  346.         outputMatrix(choiceForOutput, pathToOut, matrix, size);
  347.         outputAdjacencyMatrix(choiceForOutput, pathToOut, adjacencyMatrix, size);
  348.     }
  349.  
  350.     public static void main (String[] args) throws FileNotFoundException {
  351.         outputTaskInfo();
  352.         int[][] matrix = processUserInput();
  353.         int[][] adjacencyMatrix = ConvertMatrix(matrix.length, matrix);
  354.         processUserOutput(matrix.length, matrix, adjacencyMatrix);
  355.  
  356.         scan.close();
  357.     }
  358. }
  359.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement