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("Данная программа \"переворачивает\" действительную квадратную матрицу порядка 2*n, где 2*n задано." + "\n" + "Диапазон ввода значений размера матрицы(2 * 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 + "! \n"); isIncorrect = true; } } while (isIncorrect); return size; } public static int readSizeFromFile(final String path) { int size; boolean isIncorrect = true; System.out.println("Происходит чтение размеров матрицы..."); try (BufferedReader br = new BufferedReader(new FileReader(path))) { size = Integer.parseInt(br.readLine()); } catch (Exception e) { isIncorrect = false; 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[][] createNewMatrix(final int size, final int[][] matrix) { int[][] newMatrix = new int[size][size]; int submatrixSize = size / 2; int[][] submatrix1 = new int[submatrixSize][submatrixSize]; int[][] submatrix2 = new int[submatrixSize][submatrixSize]; int[][] submatrix3 = new int[submatrixSize][submatrixSize]; int[][] submatrix4 = new int[submatrixSize][submatrixSize]; //создание подматриц for (int i = 0; i < submatrixSize; i++) System.arraycopy(matrix[i], 0, submatrix1[i], 0, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(matrix[i], submatrixSize, submatrix2[i], 0, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(matrix[i + submatrixSize], 0, submatrix3[i], 0, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(matrix[i + submatrixSize], submatrixSize, submatrix4[i], 0, submatrixSize); //создание новой матрицы for (int i = 0; i < submatrixSize; i++) System.arraycopy(submatrix1[i], 0, newMatrix[i + submatrixSize], 0, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(submatrix2[i], 0, newMatrix[i + submatrixSize], submatrixSize, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(submatrix3[i], 0, newMatrix[i], submatrixSize, submatrixSize); for (int i = 0; i < submatrixSize; i++) System.arraycopy(submatrix4[i], 0, newMatrix[i], 0, submatrixSize); return newMatrix; } public static void outputNewMatrix(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 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[][] newMatrix) { 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); outputNewMatrix(choiceForOutput, pathToOut, newMatrix, size); } public static void main (String[] args) throws FileNotFoundException { outputTaskInfo(); inpData data = processUserInput(); int[][] newMatrix = createNewMatrix(data.size, data.matrix); processUserOutput(data.size, data.matrix, newMatrix); scan.close(); } }