Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.util.Scanner;
- public class Main {
- private static final Scanner scan = new Scanner(System.in);
- public static void main(String[] args) {
- welcome();
- int source = takeInputSource();
- int[][] matrix = takeMatrix(source);
- Node[] arr = findArray(matrix);
- source = takeOutputSource();
- output(source, arr);
- }
- public static void welcome() {
- System.out.println();
- System.out.println("ВAC ПРИВЕТСТВУЕТ ПРОГРАММА ПЕРЕВОДА МАТРИЦЫ СМЕЖНОСТИ В СПИСКИ ИНЦИНДЕНЦИЙ");
- }
- public static int takeInputSource() {
- int source = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- System.out.print("\nВыберите источник матрицы:\n1. Файл\n2. Консоль\nВаш выбор: ");
- try {
- source = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- if (!isInCorrect && (source != 2 && source != 1)) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return source;
- }
- public static int takeOutputSource() {
- int source = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- System.out.print("\nВыберите способ вывода:\n1. Файл\n2. Консоль\nВаш выбор: ");
- try {
- source = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- if (!isInCorrect && (source != 2 && source != 1)) {
- System.out.print("\nОшибка! Число введено некорректно.\n");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return source;
- }
- private static String takeInPath() {
- String path;
- boolean isIncorrect;
- System.out.print("\nВведите путь к файлу: ");
- do {
- isIncorrect = false;
- path = scan.nextLine();
- if (Files.notExists(Path.of(path))) {
- System.out.print("Файл не найден\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- if (!isIncorrect && (!path.endsWith(".txt"))) {
- System.out.print("Файл найден, но он нетипа \".txt\"\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- }while (isIncorrect);
- return path;
- }
- static String takeOutPath() {
- String path;
- boolean isIncorrect;
- System.out.print("\nВведите путь к файлу: ");
- do {
- isIncorrect = false;
- path = scan.nextLine();
- if (!path.endsWith(".txt")) {
- System.out.print("Это должен быть \".txt\" файл\nВведите путь к файлу: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- private static int takeInt(final int MIN_VALUE, final int MAX_VALUE) {
- int num = 0;
- boolean isInCorrect;
- do {
- isInCorrect = false;
- try {
- num = Integer.parseInt(scan.nextLine());
- } catch (NumberFormatException e) {
- System.out.print("Ошибка! Введите число повторно: ");
- isInCorrect = true;
- }
- if (!isInCorrect && (num < MIN_VALUE || num > MAX_VALUE)) {
- System.out.print("Ошибка! Введите число из диапазона[" + MIN_VALUE + "," + MAX_VALUE + "]: ");
- isInCorrect = true;
- }
- } while(isInCorrect);
- return num;
- }
- private static int[][] takeMatrix(int source) {
- int[][] matrix;
- if (source == 1) {
- String path = takeInPath();
- matrix = takeMatrixFromFile(path);
- while (matrix == null) {
- path = takeInPath();
- matrix = takeMatrixFromFile(path);
- }
- }
- else {
- System.out.print("\nВведите количество вершин графа: ");
- int size = takeInt(2,13);
- matrix = takeMatrixFromConsole(size);
- }
- return matrix;
- }
- private static int[][] takeMatrixFromFile(final String path) {
- int[][] matrix = null;
- int size = 0;
- int lineCounter = 0;
- boolean isCorrect = true;
- try(BufferedReader reader = new BufferedReader(new FileReader(path))) {
- size = Integer.parseInt(reader.readLine());
- lineCounter++;
- if ((size < 2) || (size > 13)) {
- isCorrect = false;
- System.out.println("Некорректные данные!!");
- }
- else {
- matrix = new int[size][size];
- while (isCorrect && lineCounter < size + 1) {
- try {
- String[] line = reader.readLine().split(" ");
- for (int i = 0; i < line.length; i++) {
- matrix[lineCounter - 1][i] = Integer.parseInt(line[i]);
- if ((lineCounter - 1 > i) && (matrix[lineCounter - 1][i] != matrix[i][lineCounter - 1])) {
- System.out.println("\nМатрица заполнена неверно!");
- isCorrect = false;
- }
- }
- lineCounter++;
- }
- catch (Exception e) {
- System.out.println("\nНекорректные данные!!");
- isCorrect = false;
- }
- }
- }
- }catch (Exception e) {
- System.out.println("\nОшибка ввода/вывода!!");
- isCorrect = false;
- }
- if (!isCorrect || (lineCounter != size + 1)) {
- matrix = null;
- }
- return matrix;
- }
- private static int[][] takeMatrixFromConsole(final int size) {
- int[][] matrix = new int[size][size];
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- matrix[i][j] = 0;
- }
- }
- for (int i = 0; i < size; i++) {
- int j = -1;
- while (j != 0) {
- System.out.print("\nВведите номер вершины, с которой связана вершина " + (i + 1) + ". Если хотите прекратить, введите 0: ");
- j = takeInt(0, size);
- if (j != 0) {
- if ( matrix[i][j - 1] == 1) {
- System.out.println("Эта вершина уже записана");
- j = -1;
- }
- else {
- System.out.println("Связь вершин " + (i + 1) + " и " + j + " записана успешно");
- matrix[i][j-1] = 1;
- matrix[j-1][i] = 1;
- }
- }
- }
- }
- return matrix;
- }
- private static Node[] findArray(int[][] matrix) {
- Node[] arr = new Node[matrix.length];
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- if (matrix[i][j] == 1) {
- Node newNode = new Node();
- newNode.setValue(j + 1);
- if (arr[i] == null) {
- arr[i] = newNode;
- }
- else {
- Node currentNode = arr[i];
- while (currentNode.getpNext() != null) {
- currentNode = currentNode.getpNext();
- }
- currentNode.setpNext(newNode);
- }
- }
- }
- }
- return arr;
- }
- private static void output(int source, Node[] arr) {
- if (source == 1) {
- String path = takeOutPath();
- outputToFile(path, arr);
- }
- else {
- outputToConsole(arr);
- }
- }
- private static void outputToConsole(Node[] arr) {
- System.out.println("Списки инцинденций:");
- for (int i = 0; i < arr.length; i++) {
- System.out.print(i + 1 + ": ");
- Node currentNode = arr[i];
- while (currentNode.getpNext() != null) {
- System.out.print(currentNode.getValue() + " -> ");
- currentNode = currentNode.getpNext();
- }
- System.out.println(currentNode.getValue());
- }
- }
- static void outputToFile(final String path, final Node[] arr) {
- try (FileWriter fw = new FileWriter(path)) {
- fw.write("Списки инцинденций:\n");
- for (int i = 0; i < arr.length; i++) {
- fw.write(i + 1 + ": ");
- Node currentNode = arr[i];
- while (currentNode.getpNext() != null) {
- fw.write(currentNode.getValue() + " -> ");
- currentNode = currentNode.getpNext();
- }
- fw.write(currentNode.getValue() + "\n");
- }
- System.out.println("Запись в файл прошла в штатном режиме :)");
- } catch (Exception e) {
- System.out.println("Ошибка при записи в файл!\nЗапись произведена в консоль:\n");
- outputToConsole(arr);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement