import java.util.Scanner; import java.io.*; final class inpData { public int size; public int[][] matrix; public inpData(int size, int[][] matrix) { this.size = size; this.matrix = matrix; } } public class Main { private static final int MIN_SIZE = 2; private static final int MAX_SIZE = 10; private static final int MIN_VALUE = -1000; private static final int MAX_VALUE = 1000; private static final Scanner scan = new Scanner(System.in); public static void outputTaskInfo() { System.out.println("Данная программа находит определитель заданной матрицы." + "\n" + "Диапазон ввода значений порядка матрицы : " + MIN_SIZE + "..." + MAX_SIZE + ". \n" + "Диапазон ввода значений элементов матрицы: " + MIN_VALUE + "..." + MAX_VALUE + "."); } 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 + "!"); 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()); if (size < MIN_SIZE || size > MAX_SIZE) { System.out.println("Ошибка при считывании размера из файла!Введите размер с консоли!"); size = readSizeFromConsole(); } } 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.println("Введите значение элемента " + (i + 1) + "-ой строки " + (j + 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] < MIN_VALUE || matrix[i][j] > MAX_VALUE)) { isIncorrect = true; System.out.println("Введите число от " + MIN_VALUE + " до " + MAX_VALUE + "!"); } } 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] > MAX_VALUE) { 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++) { 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); for (int i = 0; i < size; i++) { 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 findDeterminant(final int[][] matrix){ int i, j, m, counter, k, sum, sign; sum = 0; if (matrix.length == 1) { sum = matrix[0][0]; } else { int[][] minor = new int[matrix.length - 1][matrix.length - 1]; counter = 0; for (k = 0; k < matrix.length; k++) { sign = -1; for (m = 0; m < k + 1; m++) sign = -sign; for (i = 1; i < matrix.length; i++) for (j = 0; j < matrix.length; j++) if (j != k) { minor[i - 1][counter % (matrix.length - 1)] = matrix[i][j]; counter++; } sum += sign * matrix[0][k] * findDeterminant(minor); } } return sum; } public static void outputDeterminant(final int choice, String path, final int determinant) { boolean isIncorrect; if (choice == 0) System.out.println("Определитель матрицы равен " + determinant + "."); if (choice == 1) { System.out.println("Вывод значения определителя матрицы в файл..."); do { isIncorrect = false; try { FileWriter writer = new FileWriter(path); writer.write(determinant + "\n"); writer.close(); } catch (IOException e) { isIncorrect = true; System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!"); path = inputPathToFile(); } } while (isIncorrect); System.out.println("Данные успешно записаны в файл!"); } } public static inpData 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 new inpData(size, matrix); } public static void processUserOutput(int size, int[][] matrix, int determinant) { 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); outputDeterminant(choiceForOutput, pathToOut, determinant); } public static void main (String[] args) throws FileNotFoundException { outputTaskInfo(); inpData data = processUserInput(); int determinant = findDeterminant(data.matrix); processUserOutput(data.size, data.matrix, determinant); scan.close(); } }