import java.util.ArrayList; import java.util.Scanner; import java.io.*; public class Main { private static final int MIN_SIZE = 1; private static final int MAX_SIZE = 9; private static final int MIN_VALUE = 0; private static final Scanner scan = new Scanner(System.in); public static void outputTaskInfo() { System.out.println("Данная программа преобразует данные списки инцидентности в матрицу смежности." + "\n" + "Диапазон ввода значения количества вершин: " + MIN_SIZE + "..." + MAX_SIZE + "."); } public static int getVerificationOfChoice() { int choice = 0; boolean isIncorrect; do { isIncorrect = false; try { choice = Integer.parseInt(scan.nextLine()); } catch (NumberFormatException e) { System.out.println("Проверьте корректность ввода данных!"); isIncorrect = true; } if (!isIncorrect && (choice != 0 && choice != 1)) { System.out.println("Для выбора введите 0 или 1!"); isIncorrect = true; } } while (isIncorrect); return choice; } public static String inputPathToFile() { boolean isIncorrect; String path; System.out.println("Укажите путь к файлу: "); do { isIncorrect = false; path = scan.nextLine(); File file = new File(path); if (!file.exists()) { System.out.println("По указанному пути файл не найден! Укажите правильный путь: "); isIncorrect = true; } } while (isIncorrect); return path; } public static int readSizeFromConsole(){ int size = 0; boolean isIncorrect; System.out.println("Введите значение размера матрицы: "); do { isIncorrect = false; try { size = Integer.parseInt(scan.nextLine()); } catch (NumberFormatException e) { System.out.println("Проверьте корректность ввода данных!"); isIncorrect = true; } if (!isIncorrect && (size < MIN_SIZE || size > MAX_SIZE)) { System.out.println("Введите число от " + MIN_SIZE + " до " + MAX_SIZE + "! \n"); isIncorrect = true; } } while (isIncorrect); return size; } public static int readSizeFromFile(final String path) { int size; System.out.println("Происходит чтение количества вершин..."); try (BufferedReader br = new BufferedReader(new FileReader(path))) { size = Integer.parseInt(br.readLine()); } catch (Exception e) { System.out.println("Ошибка при считывании количества вершин из файла!Введите количество с консоли!"); size = readSizeFromConsole(); } return size; } public static void outputSize(final int choice, int size, String path) { boolean isIncorrect; if (choice == 0) System.out.println("Количество вершин равно " + size + "."); if (choice == 1) { System.out.println("Вывод значения количества вершин в файл..."); do { isIncorrect = false; try { FileWriter writer = new FileWriter(path); writer.write("Кол-во вершин: " + size + "\n"); writer.close(); } catch (IOException e) { isIncorrect = true; System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); path = inputPathToFile(); } } while (isIncorrect); System.out.println("Данные успешно записаны в файл!"); } } public static int[][] fillMatrixFromConsole(final int size) { int[][] matrix = new int[size][size]; boolean isIncorrect; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print("Введите " + (j + 1) + "-ое значение для " + (i + 1) + "-ой вершины: " ); do { isIncorrect = false; try { matrix[i][j] = Integer.parseInt(scan.nextLine()); } catch (NumberFormatException e) { System.out.println("Проверьте корректность ввода данных!"); isIncorrect = true; } if (!isIncorrect && (matrix[i][j] < 0 || matrix[i][j] > size)) { isIncorrect = true; System.out.println("Введите значение от " + MIN_VALUE + " до " + size + "!"); } } while (isIncorrect); } } return matrix; } public static int[][] fillMatrixFromFile (final int size, final String path) throws FileNotFoundException { int[][] matrix = new int[size][size]; int count = 0 ; Scanner fr = new Scanner(new File(path)); System.out.println("Чтение списков инцидентности ..."); fr.nextLine(); while (fr.hasNext()) { fr.next(); count++; } fr.close(); if (count > size * size) { System.out.println("Ошибка при чтении списков инцидентности! Введите списки с консоли!"); matrix = fillMatrixFromConsole(size); } else { fr = new Scanner(new File(path)); fr.nextLine(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { try { matrix[i][j] = fr.nextInt(); } catch (Exception e) { System.out.println("Ошибка при считывании списков инцидентности из файла!Введите списки с консоли!"); matrix = fillMatrixFromConsole(size); } if (matrix[i][j] < MIN_VALUE || matrix[i][j] > size) { System.out.println("Ошибка при считывании списков инцидентности из файла! Введите списки с консоли!"); matrix = fillMatrixFromConsole(size); } } } } return matrix; } public static void outputMatrix(final int choice, String path, final int[][] matrix, final int size) { boolean isIncorrect; if (choice == 0) { System.out.println("Вывод списков инцидентности: "); for (int i = 0; i < size; i++) { int j = 0; System.out.print((i + 1) + "-ая вершина: "); while (j < size && matrix[i][j] > 0) { System.out.print(matrix[i][j] + " -> "); j++; } System.out.println("nil"); } } if (choice == 1) { System.out.println("Вывод списков инцидентности в файл..."); do { isIncorrect = false; try { FileWriter writer = new FileWriter(path, true); BufferedWriter bufferWriter = new BufferedWriter(writer); for (int i = 0; i < size; i++) { int j = 0; bufferWriter.write((i + 1) + "-ая вершина: "); while (j < size && matrix[i][j] > 0) { bufferWriter.write(matrix[i][j] + " -> "); j++; } bufferWriter.write("nil\n"); } bufferWriter.close(); writer.close(); } catch (IOException e) { isIncorrect = true; System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); path = inputPathToFile(); } } while (isIncorrect); System.out.println("Данные успешно записаны в файл!"); } } public static int[][] ConvertMatrix(final int size, final int[][] matrix){ int[][] adjacencyMatrix = new int [size][size]; for (int i = 0; i < size; i++) { int j = 0; while (j < size) { adjacencyMatrix[i][j] = 0; j++; } j = 0; while (j < size && matrix[i][j] != 0) { adjacencyMatrix[i][matrix[i][j] - 1] = 1; j++; } } return adjacencyMatrix; } public static void outputAdjacencyMatrix(final int choice, String path, final int[][] matrix, final int size) { boolean isIncorrect; if (choice == 0) { System.out.println("Вывод матрицы смежности: "); System.out.print("\t"); for (int i = 0; i < size; i++) { System.out.print((i + 1) + "\t"); } System.out.print("\n"); for (int i = 0; i < size; i++) { System.out.print((i + 1) + "\t"); for (int j = 0; j < size; j++) System.out.print(matrix[i][j] + "\t"); System.out.print("\n"); } System.out.print("\n"); } if (choice == 1) { System.out.println("Вывод матрицы смежности в файл..."); do { isIncorrect = false; try { FileWriter writer = new FileWriter(path, true); BufferedWriter bufferWriter = new BufferedWriter(writer); bufferWriter.write("\t"); for (int i = 0; i < size; i++) { bufferWriter.write((i + 1) + "\t"); } bufferWriter.write("\n"); for (int i = 0; i < size; i++) { bufferWriter.write((i + 1) + "\t"); for (int j = 0; j < size; j++) bufferWriter.write(matrix[i][j] + "\t"); bufferWriter.write("\n"); } bufferWriter.write("\n"); bufferWriter.close(); writer.close(); } catch (IOException e) { isIncorrect = true; System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); path = inputPathToFile(); } } while (isIncorrect); System.out.println("Данные успешно записаны в файл!"); } } public static int[][] processUserInput() throws FileNotFoundException { int size = 0; int choiceForInput; int[][] matrix = new int[0][]; String pathToIn = ""; System.out.println("Вы желаете ввести данные с консоли(0) или взять данные из файла(1)?"); choiceForInput = getVerificationOfChoice(); if (choiceForInput == 0) { size = readSizeFromConsole(); matrix = fillMatrixFromConsole(size); } if (choiceForInput == 1) { pathToIn = inputPathToFile(); size = readSizeFromFile(pathToIn); matrix = fillMatrixFromFile(size, pathToIn); } return matrix; } public static void processUserOutput(int size, int[][] matrix, int[][] adjacencyMatrix) { int choiceForOutput; String pathToOut = ""; System.out.println("Вы желаете получить результат в консоли(0) или в файле(1)?"); choiceForOutput = getVerificationOfChoice(); if (choiceForOutput == 1) pathToOut = inputPathToFile(); outputSize(choiceForOutput, size, pathToOut); outputMatrix(choiceForOutput, pathToOut, matrix, size); outputAdjacencyMatrix(choiceForOutput, pathToOut, adjacencyMatrix, size); } public static void main (String[] args) throws FileNotFoundException { outputTaskInfo(); int[][] matrix = processUserInput(); int[][] adjacencyMatrix = ConvertMatrix(matrix.length, matrix); processUserOutput(matrix.length, matrix, adjacencyMatrix); scan.close(); } }